Safe usage of Sanity write tokens in frontend vs backend
Your understanding is 100% correct! 🎯
Write tokens (including robot user tokens with write access) should never be included in frontend bundles like Gatsby, Next.js client components, or any client-side JavaScript. This is a critical security principle.
The proper approach is exactly what you described:
- Create an API endpoint (serverless function, backend route, etc.) that keeps the write token server-side
- Store the token securely in environment variables on your server
- Client code calls your API with the necessary data
- Your API validates the request and uses the write token to make changes in Sanity
This pattern works great with:
- Serverless functions (Vercel, Netlify, AWS Lambda)
- API routes (Next.js API routes, Express endpoints, etc.)
- Sanity Functions (serverless compute built directly into Sanity - great for event-driven workflows)
Why this matters: If you expose a write token in your frontend bundle, anyone can inspect your JavaScript, extract the token, and have full write access to your Sanity project. They could delete, modify, or create any content.
For read-only access: If you only need to fetch published content, you can use a read-only token (Viewer role) directly in the frontend, though many projects work fine without any token for public content. For accessing draft content in preview mode, you'd still want that token server-side or at least carefully scoped.
The API tokens documentation covers token security best practices in detail, and the principle of least privilege applies - only give tokens the minimum permissions they need for their specific use case.
Show original thread3 replies
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.