Handy TypeScript Module for Sanity

Originally published on 13 February, 2021 by Jacob Stordahl

Create a file called SanityClient.ts somewhere in your TS project, with the following code...

import sanityClient from '@sanity/client';

type Client = {
  projectId: string,
  dataset: string,
  token: string,
  useCdn: boolean
}

// create instance of sanityClient
// this is how you connect your frontend to your sanity studio
const options:Client = {
  //your project ID
  projectId: '',
  //your dataset; defaults to production
  dataset: 'production',
  token: '',
  useCdn: true
}

const client = sanityClient( options );

export { client }

Simply place your projectId within the module, then you can then import this module anywhere in your project. Where ever it's imported, you can use it like so...

import { client } from './SanityClient.ts'

const query = '*[_type = product]'

const res = client.fetch(query)
© 2021 Jacob Stordahl | built with Steel