How to get Auth token for export data API in Node.js?

8 replies
Last updated: Apr 18, 2024
Anybody know how to get Auth token to then call the export data api using nodejs?
AI Update

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:

  1. Access Sanity Manage by running npx sanity@latest manage from your project directory, or access it from your Studio menu

  2. Navigate to the "API" tab

  3. 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
  4. 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.ndjson

The full Export API documentation is available at the Sanity Export API reference.

Show original thread
8 replies
import exportDataset from '@sanity/export';
import {createClient} from '@sanity/client';

const configTemplate = {
    // Instance of @sanity/client configured to correct project ID and dataset
    client: createClient({
        projectId: process.env.projectId,
        dataset: process.env.datasetName,
        useCdn: false, // set to `true` to fetch from edge cache
        apiVersion: '2022-01-12', // use current date (YYYY-MM-DD) to target the latest API version
        token: process.env.API_TOKEN
    }),

    // Name of dataset to export
    dataset: process.env.datasetName,

    // Path to write tar.gz-archive file to, or `-` for stdout
    outputPath: process.env.outputPath,

    // Whether or not to export assets. Note that this operation is currently slightly lossy;
    // metadata stored on the asset document itself (original filename, for instance) might be lost
    // Default: `true`
    assets: true,

    // Exports documents only, without downloading or rewriting asset references
    // Default: `false`
    raw: false,

    // Whether or not to export drafts
    // Default: `true`
    drafts: true,

    // Export only given document types (`_type`)
    // Optional, default: all types
    // types: ['products', 'shops'],

    // Run 12 concurrent asset downloads
    assetConcurrency: 12
};

await exportDataset(configTemplate);
user J
Im getting
exportDataset
is not a function
You need to install.
"@sanity/export"

npm install @sanity/export
I already have. I got version
3.37.3
I'm running 3.34 doubtful. thats the issue
https://github.com/sanity-io/export Maybe try
const exportDataset = require('@sanity/export');
Don't know without seeing your code, even then JS isn't my best language
Yea it needed to be require. That works. Thanks!

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?