How to securely send requests to Sanity in a Next.js app using API routes.
Last updated: Sep 29, 2023
hello, I am working on nextjs+ embeded Sanity. I came across a problem. I have a Review component. On button click I want to send a request to sanity to create new review document. And here is the issue. I can only send a request if token is added directly to the client. If I add token to my .env file I get error that I don't have permission. Any ideas what to do in this case? I use Nextjs with app directory
Sep 29, 2023, 12:27 PM
. The Sanity client can freely read information, but you need an API key to perform writes. That being said, you should not expose security-sensitive API keys to the client. The correct route in your case would be to use a Next API route , having your write key as a non-public environment variable (i.e. not starting with
). You would then call your own API route to achieve the behaviour you want
Sep 29, 2023, 12:58 PM
I see, Thank you for your answer!
Sep 29, 2023, 1:02 PM
Sure thing. Let me know if you need any further help