How to get Auth token for export data API in Node.js?
To call the Sanity Export Data API using Node.js, you'll need to authenticate your request with an API token. Here's how to get set up:
Creating an API Token
You need to create an API token in your Sanity project management interface:
Access Sanity Manage by running
npx sanity@latest managefrom your project directory, or access it from your Studio menuNavigate to the "API" tab
Create a new token and assign it appropriate permissions:
- For read-only access (which is what you need for exports), assign Viewer permissions
- For write access, you'd need Editor or higher permissions
Copy the token and store it securely in your environment variables
Using the Token with the Export API
Here's how to call the export API in Node.js:
import https from 'https';
const projectId = 'your-project-id';
const dataset = 'production'; // or your dataset name
const token = process.env.SANITY_API_TOKEN; // Store your token in env vars
const apiVersion = 'v2021-03-25';
const options = {
hostname: `${projectId}.api.sanity.io`,
path: `/${apiVersion}/data/export/${dataset}`,
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
};
const req = https.request(options, (res) => {
res.on('data', (chunk) => {
// Process NDJSON stream
console.log(chunk.toString());
});
});
req.on('error', (error) => {
console.error(error);
});
req.end();Best Practices
- Never hardcode tokens in your source code - always use environment variables
- Use the appropriate token type: For production/automated systems, create a Robot token rather than a personal token
- Follow least privilege: Only assign the minimum permissions needed (Viewer for exports)
- The export endpoint returns an NDJSON stream (newline-delimited JSON)
Alternative: Use the Sanity CLI
For most export use cases, you might find it easier to use the Sanity CLI's built-in export command, which handles authentication automatically if you're logged in:
sanity dataset export production export.ndjsonThe full Export API documentation is available at the Sanity Export API reference.
Show original thread8 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.