Search code examples
nestjssanity

How to query Sanity client with NestJS?


Right now I have React app initialized with Vite connected with Sanity. Everything is working just fine, Sanity client is connected, React is fetching data from Sanity, I'm receiving it with no problem. enter image description here

But the problem is, that if I deploy React app with Sanity connected, then I will leak my projectID and sanity_token to the fronted, which I want to avoid of course.

So I have to make some backend REST API which will be fetched by React, and then my API will fetch Sanity. I could do it with Node.js and Express without problem, but I decided that I will use NestJS and learn something instead.

enter image description here

But when it comes to NestJS, everything is connected a bit different.

On the front I had :

import sanityClient from '@sanity/client';

export const client = sanityClient({
  projectId: import.meta.env.VITE_SANITY_PROJECT_ID, 
  dataset: 'production',
  apiVersion: '2022-02-01', 
  useCdn: true,
  token: import.meta.env.VITE_SANITY_TOKEN
});

And for NestJS I found something like this:

import { Injectable } from '@nestjs/common';
import sanityClient, { SanityClient } from '@sanity/client';

@Injectable()
export class SanityService {
  public readonly client: SanityClient = sanityClient({
    projectId: process.env.SANITY_PROJECT_ID, 
    dataset: 'production',
    apiVersion: '2022-02-01', 
    useCdn: true,
    token: process.env.SANITY_TOKEN
  });
}

My question is that if it's a good way to connect Sanity client? How to query Sanity client with specified GROQ query?

Till now I was using this on the frontend, but it's not gonna work in NestJS:

const query = '*[_type == "blogPost"]';

    client.fetch(query)
      .then((data) => {
        setPosts(data);
      })
      .catch((err) => {
        console.log(err);
      })

Solution

  • It turned out that this is the proper way to connect with Sanity client, I had an issue with that similar to this thread

    And the solution was the same as in the thread above. Add "esModuleInterop": true to tsconfig.json.

    {
      "compilerOptions": {
        ...
        "esModuleInterop": true,
        ...
      }
    }
    

    Then call for data to sanity client is working properly:

      @Get()
      async getAllPosts() {
        
        // initialize sanity instance
        const sanityService = new SanityService();
    
        // your query
        const query = '*[_type == "blogPost"]';
    
        try {
          const data = await sanityService.client.fetch(query);
          
          return data;
    
        } catch (error) {
          console.log(error.msg);
        }
      }