Issue with sending comments to Sanity studio from deployed version

13 replies
Last updated: Sep 7, 2022
I created comment system with sanity and next js with the help from this tutorial on youtube from sanity youtbue channel.Its working perfect in localhost. But on my deployed version its not sending the comments to sanity studio. (Rest of content from sanity is being fetched).

here is comment.js from pages/api/comment.js:

export default async function comment(req, res) {
    const { name, text, email, _id } = JSON.parse(req.body)
    client.config({
        token: process.env.SANITY_API_TOKEN_COMMENT
    }).create({
        _type: 'comment',
        name,
        comment: text,
        email,
        post: { 
            _type:'reference',
            _ref: _id
        }
    })
    res.status(200)
}
Token I am using has Editor access as you can see in the image.

Here is the code for onClick event of submiting the comment:

const onSubmit = async (data) => {
      setIsSubmitting(true);
      try {
        await fetch("/api/comment", {
          method: "POST",
          body: JSON.stringify({ ...data, _id }),
        });
        setIsSubmitting(false);
        setHasSubmitted(true);
        setTimeout(()=>{
          setHasSubmitted(false)
        },3000)

        if(getValues('storeData')){
          window.localStorage.setItem('name',getValues('name'))
          window.localStorage.setItem('email',getValues('email'))
        }

      
    } catch (err) {
      console.log(err);
    }
so how can I'll be able to send comments from deployed version of my website?

.
AI Update

Looking at your code, the issue is almost certainly that your SANITY_API_TOKEN_COMMENT environment variable isn't configured in your production deployment environment. The code works locally because you have it set up in your local .env file, but environment variables need to be separately configured in your hosting platform.

Here are the steps to fix this:

1. Add the environment variable to your hosting platform

Depending on where you're deploying (Vercel, Netlify, etc.), you need to add SANITY_API_TOKEN_COMMENT to your production environment variables:

  • Vercel: Go to your project → Settings → Environment Variables
  • Netlify: Go to Site settings → Build & deploy → Environment variables
  • Other platforms: Look for environment variables or config settings

Make sure to use the same token value you have locally.

2. Fix a critical bug in your API route

Your API route has a problem - it's not awaiting the Sanity client's create() method and not sending a proper response. This could cause silent failures:

export default async function comment(req, res) {
    try {
        const { name, text, email, _id } = JSON.parse(req.body)
        
        await client.config({
            token: process.env.SANITY_API_TOKEN_COMMENT
        }).create({
            _type: 'comment',
            name,
            comment: text,
            email,
            post: { 
                _type: 'reference',
                _ref: _id
            }
        })
        
        return res.status(200).json({ message: 'Comment submitted' })
    } catch (error) {
        console.error(error)
        return res.status(500).json({ error: 'Failed to submit comment' })
    }
}

3. Verify the token has correct permissions

Make sure your token has:

  • Editor or Contributor permissions (which you mentioned you have)
  • No IP restrictions that might block your hosting provider's IPs

4. Check your deployment logs

Look at your serverless function logs in your hosting platform's dashboard. You'll likely see errors that reveal whether:

  • The environment variable is undefined
  • There's a network/CORS issue
  • The token is invalid

5. Redeploy after adding environment variables

After adding the environment variable, you may need to trigger a new deployment for it to take effect (some platforms require this).

The most common cause of "works locally but not in production" for Sanity mutations is missing environment variables in the deployment platform. Once you add SANITY_API_TOKEN_COMMENT to your hosting platform's environment variables and fix the await issue, your comments should start working in production.

Where do you deploy? Vercel?
Yes in vercel
Did you define your token in Vercel environment variables settings?
Yes
Would be good to have some logs.
Where can I find those logs? I am new in this
it would be great if you helped
here are they
Just to comfirm comment token should have 'Editors' access right?
Read/write, so I guess that’s Editor yes.
For the logs, I meant putting some logs in your function to understand what’s happening on Vercel. So we know if the request to Sanity fails and why.
After rechecking my entire code I just found out that I didn't used await for async function inside /api/comment.js. And now its been working.
Thanks for help!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?