
Installing the Sanity CLI and Essential Commands
You don't need to install the Sanity CLI globally. Run it with npx sanity@latest <command> (or pnpm dlx, yarn dlx or bunx), and inside a Studio project use npx sanity <command>, which runs the version installed with the sanity package. You need Node.js 22.12 or later. The essential commands are login, init, dev, build, deploy, datasets, documents, cors, tokens, schemas, typegen and exec, and npx sanity --help lists everything available.
The CLI is how developers create projects, run the Studio, manage datasets and access, move content in and out, generate TypeScript types and run scripts against the Content Lake. This guide covers installation and authentication, how the CLI finds your project, and the commands you'll use most, grouped by task, with examples you can copy.
Installing the Sanity CLI
Option 1: Run It with npx (Recommended)
The CLI is distributed through npm. The simplest approach is to run the latest version on demand:
npx sanity@latest --help
Equivalents for other package managers:
pnpm dlx sanity@latest --help
yarn dlx sanity@latest --help
bunx sanity@latest --help
This always uses the newest CLI and avoids version mismatches between machines.
Option 2: Use the Project's Local CLI
Every Studio project depends on the sanity package, which includes the CLI. Inside the project folder, npx sanity runs that local version, and the package.json scripts call it too:
"scripts": {
"dev": "sanity dev",
"start": "sanity start",
"build": "sanity build",
"deploy": "sanity deploy",
"deploy-graphql": "sanity graphql deploy"
}
Using the local version keeps your Studio and CLI in step, which matters for build and deploy. The generated start script still works, but sanity start is deprecated in favour of sanity preview.
Removing an Old Global Install
If you installed the CLI globally in the past, remove it to avoid running an outdated version by accident:
npm uninstall --global sanity
# or
yarn global remove sanity
# or
pnpm remove --global sanity
Check Your Setup
node -v
npx sanity versions
sanity versions prints the installed Sanity package versions, and sanity debug prints diagnostic details (user, project, versions) that are useful when reporting problems. sanity doctor runs checks on your project.
Logging In and Out
Most commands need you to be authenticated:
npx sanity login
The CLI opens a browser for you to sign in with Google, GitHub or email and password. Useful variations:
npx sanity login --provider github # skip the provider prompt
npx sanity login --sso my-org # log in with your organisation's SSO
npx sanity whoami # show who you're logged in as
npx sanity logout
In CI, you don't log in. Set the SANITY_AUTH_TOKEN environment variable to an API token instead, and commands like deploy use it automatically.
How the CLI Knows Which Project to Use
Project-specific commands read sanity.cli.ts in the current folder:
// sanity.cli.ts
import { defineCliConfig } from 'sanity/cli'
export default defineCliConfig({
api: {
projectId: 'abc123xy',
dataset: 'production',
},
deployment: {
autoUpdates: true,
},
})
Many commands also accept --project (or -p) and --dataset (or -d) flags to override this, which lets you run commands from outside a Studio folder. The Sanity project structure post explains how sanity.cli.ts differs from sanity.config.ts.
Creating Projects
sanity init
Creates a new project and Studio, or adds Sanity to an existing app:
npx sanity@latest init
npm create sanity@latest runs the same initializer. Useful flags for scripting:
# Non-interactive setup with a known project and dataset
npx sanity@latest init -y \
--project abc123xy \
--dataset production \
--template clean \
--typescript \
--output-path ./studio
# New project with a public "production" dataset
npx sanity@latest init --dataset-default
Run inside a Next.js app, init detects the framework and can add config files, append environment variables and embed the Studio as a route. The full walkthrough is in how to set up your first Sanity project.
sanity new
Creates a real project without an account, scaffolding a Studio in ./sanity and a Next.js site in ./web. You have 72 hours to claim it by signing up. It's handy for quick experiments:
npx sanity@latest new "My Test Project"
sanity projects
npx sanity projects list
Lists the projects you have access to, with their IDs. sanity manage opens the current project's settings in your browser.
Running and Building the Studio
| Command | What it does |
|---|---|
sanity dev | Starts the local development server with hot reloading, on port 3333 by default |
sanity build | Builds the Studio into a static bundle in dist/ |
sanity preview | Serves the production build locally so you can test it |
sanity deploy | Builds and deploys the Studio to Sanity hosting |
sanity undeploy | Removes the deployed Studio from Sanity hosting |
npx sanity dev --port 3334
npx sanity dev --host 0.0.0.0 # reachable from other devices on your network
npx sanity build
npx sanity preview
Deployment has enough options to deserve its own guide: hostnames, appId, CI tokens, --no-build, external Studios and embedding. See how to deploy Sanity Studio.
Managing Datasets
The datasets commands cover the full dataset lifecycle. The singular dataset also works as an alias.
npx sanity datasets list
npx sanity datasets create staging --visibility public
npx sanity datasets delete old-test
npx sanity datasets visibility get production
npx sanity datasets visibility set staging private
Private visibility requires a paid plan. The Content Lake explained post covers what datasets are and how visibility works.
Exporting and Importing
Export creates a gzipped tarball with an NDJSON file of documents plus asset files:
npx sanity datasets export production ./backups/production.tar.gz
Helpful export flags:
--no-assets: skip asset files, for a smaller documents-only export.--no-drafts: export only published documents.--types post,author: export only some document types.--overwrite: replace an existing file.
Import into another dataset:
npx sanity datasets import ./backups/production.tar.gz --dataset staging --replace
--replace overwrites documents with the same IDs, while --missing skips documents that already exist. You can also import a plain .ndjson file. Exports count against your API request quota.
Copying a Dataset
npx sanity datasets copy production staging
Copies a dataset in the cloud, including document history unless you pass --skip-history. Cloud copying is an advanced feature that isn't available on every plan; export and import works everywhere.
Working with Documents
The documents commands let you inspect content without opening the Studio:
# Run a GROQ query
npx sanity documents query '*[_type == "post"][0...5]{title, "slug": slug.current}'
# Query another dataset
npx sanity documents query '*[_type == "post"] | order(_updatedAt desc)[0]{title}' --dataset staging
# Fetch one document by ID
npx sanity documents get siteSettings --pretty
# Validate every document against the Studio schema
npx sanity documents validate
documents create and documents delete are also available for quick fixes. Queries run with your user token, so they can see drafts. Add --anonymous to see what the public sees. For learning GROQ itself, the GROQ cheat sheet is a good companion.
CORS Origins
Browsers can only query your project from allowed origins. Manage them with:
npx sanity cors list
npx sanity cors add http://localhost:3000 --no-credentials
npx sanity cors add https://studio.example.com --credentials
npx sanity cors delete
Allow credentials only for origins that host a Studio or need to send user tokens or cookies. A normal website reading public content doesn't need them.
API Tokens
Tokens let servers, build tools and scripts authenticate:
npx sanity tokens list
npx sanity tokens create "Next.js read token" --role viewer
npx sanity tokens rotate
npx sanity tokens delete
Give each token the smallest role it needs: Viewer for reading drafts in previews, Editor for scripts that write content. Tokens are shown once, so store them straight away in your environment variables. Never put a write token in browser code.
Users and Webhooks
npx sanity users list
npx sanity users invite colleague@example.com --role editor
npx sanity hooks list
npx sanity hooks create
npx sanity hooks logs
Webhooks are often used to trigger a site rebuild when content is published. hooks logs and hooks attempt help debug failed deliveries.
Schemas and TypeScript Types
Validating and Extracting Schemas
npx sanity schemas validate
npx sanity schemas extract
validate checks your schema for errors and warnings without starting the Studio, which is useful in CI. extract writes a schema.json file describing your schema.
Generating Types with TypeGen
TypeGen reads that extracted schema and your GROQ queries and generates TypeScript types:
npx sanity schemas extract
npx sanity typegen generate
By default it scans ./src/**/*.{ts,tsx,js,jsx} for queries defined with defineQuery (or the groq tag) and writes sanity.types.ts. You can change paths in a sanity-typegen.json file. In your front end, typed queries look like this:
import { defineQuery } from 'next-sanity'
export const POSTS_QUERY = defineQuery(
`*[_type == "post" && defined(slug.current)]{ _id, title, "slug": slug.current }`,
)
After running TypeGen, client.fetch(POSTS_QUERY) returns a typed result automatically. Add --watch to regenerate as you edit.
Deploying Schemas
npx sanity schemas deploy
Uploads your schema to the Content Lake so that platform features outside the Studio, such as the Dashboard, Canvas and AI tools, understand your content model. sanity deploy does this for you as part of a Studio deploy. If you use the GraphQL API, deploy it separately:
npx sanity graphql deploy
Running Scripts and Migrations
sanity exec
Runs a script with your project's configuration available, which is perfect for one-off data fixes:
// scripts/add-default-category.ts
import { getCliClient } from 'sanity/cli'
const client = getCliClient({ apiVersion: '2026-10-01' })
const ids: string[] = await client.fetch(`*[_type == "post" && !defined(category)]._id`)
const tx = client.transaction()
ids.forEach((id) => tx.patch(id, (p) => p.set({ category: { _type: 'reference', _ref: 'general' } })))
await tx.commit()
console.log(`Updated ${ids.length} posts`)
npx sanity exec scripts/add-default-category.ts --with-user-token
--with-user-token makes getCliClient() use your logged-in session, so you don't need to create a token.
sanity migrations
For repeatable, reviewable changes to content structure, use the migration tooling:
npx sanity migrations create "Rename author bio"
npx sanity migrations list
npx sanity migrations run rename-author-bio
migrations run performs a dry run by default and shows what would change. Add --no-dry-run when you're ready to apply it.
Other Useful Commands
| Command | Purpose |
|---|---|
sanity docs | Search and read Sanity documentation in the terminal |
sanity learn | Open Sanity Learn in the browser |
sanity codemod | Run code modification scripts when upgrading |
sanity install | Install dependencies for the Studio project |
sanity backups | Enable, list and download dataset backups, where your plan supports them |
sanity functions | Develop, test and view logs for Sanity Functions |
sanity blueprints | Manage the infrastructure definitions that deploy Functions |
sanity mcp | Configure the Sanity MCP server for AI coding tools |
Any command accepts --help for its full list of flags, for example npx sanity datasets export --help.
FAQ: Sanity CLI
It isn't necessary. Run commands with npx sanity@latest outside a project and npx sanity inside one, which uses the version installed with your Studio. This avoids an outdated global version causing confusing errors.
Current versions of the Sanity CLI and Studio require Node.js 22.12 or later. Older versions fail with an error, so check with node -v and upgrade to the current LTS release if needed.
Create an API token with the permissions the job needs and set it as the SANITY_AUTH_TOKEN environment variable in your pipeline. Commands such as deploy then authenticate with it instead of an interactive login.
Run npx sanity datasets export followed by the dataset name and an output file path. The tarball contains all documents and asset files, and you can restore it with npx sanity datasets import.
The command runs with your user token, which can read draft documents. Add the anonymous flag to send the query without a token and see only what public visitors can read.
sanity build compiles the Studio into static files in the dist folder, which you can host anywhere. sanity deploy builds the Studio and uploads it to Sanity's hosting on a sanity.studio URL in one step.
Conclusion
The Sanity CLI needs no global installation: npx sanity@latest for new work and the project's local npx sanity for everything else. With login, init and dev you can be running in minutes, and build, deploy, datasets, documents, cors and tokens cover most day-to-day project management.
As your project grows, schemas, typegen, exec and migrations become just as important, giving you type safety and a safe, scripted way to change content. Keep --help close at hand, since flags evolve between versions and every command documents its own options.


