> For AI agents: the complete Sanity documentation index is available at [https://www.sanity.io/docs/llms.txt](https://www.sanity.io/docs/llms.txt).

# Getting started with @sanity/client

Learn how to install and configure the official Sanity JavaScript client for querying and mutating content across different environments.

The @sanity/client library is the official JavaScript client for interacting with Sanity's APIs. It provides a type-safe way to query and mutate your content from any JavaScript environment, including browsers, Node.js, Deno, Bun, and edge runtimes.

With @sanity/client, you can:

- [Query content](https://www.sanity.io/docs/apis-and-sdks/js-client-querying) using GROQ to fetch exactly the data you need.
- [Mutate documents](https://www.sanity.io/docs/apis-and-sdks/js-client-mutations) by creating, updating, patching, and deleting content programmatically.
- [Upload assets](https://www.sanity.io/docs/apis-and-sdks/js-client-assets) like images and files to your Sanity project.
- [Listen to real-time updates](https://www.sanity.io/docs/apis-and-sdks/js-client-realtime) and react to changes in your content as they happen.

## Requirements

To use the client, you need:

- A JavaScript runtime: Node.js 22.12 or later, modern browsers, Bun, Deno, or edge runtimes.
- A Sanity project with a project ID and dataset name.
- An API token (optional, required only for authenticated requests like mutations or accessing private datasets).
- TypeScript projects: `moduleResolution` set to `node16`, `nodenext`, or `bundler` in `tsconfig.json`.

These requirements apply to `@sanity/client` v8 and later. If you can't move to a newer Node.js version, stay on v7. The [v8 migration guide](https://github.com/sanity-io/client/blob/main/docs/MIGRATE-v7.md) covers each breaking change.

> [!TIP]
> If you want to use the client library with a framework, we have optimized versions for [Next.js](https://github.com/sanity-io/next-sanity), [Astro](https://github.com/sanity-io/sanity-astro), or [SvelteKit](https://github.com/sanity-io/sanity-sveltekit).

## Installation

Install `@sanity/client` using your preferred package manager:

**npm**

```shell
npm install @sanity/client
```

**pnpm**

```shell
pnpm add @sanity/client
```

**yarn**

```shell
yarn add @sanity/client
```

**bun**

```shell
bun add @sanity/client
```

## Basic client setup

Create a client instance using the `createClient()` function with your project configuration:

**sanity.ts**

```typescript
import {createClient} from '@sanity/client'

export const client = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'YOUR_DATASET',
  useCdn: true,
  apiVersion: '2026-03-01',
})
```

## Query with the client

Use `client.fetch` to query content from Content Lake.

**query.ts**

```typescript
import {client} from './sanity'

const QUERY = `*[_type == "post"]`

try {
  const posts = await client.fetch(QUERY)
  console.log(posts)
} catch (error) {
  console.error('Query failed:', error)
}
```

You can learn more about fetching content in the [querying content guide](https://www.sanity.io/docs/apis-and-sdks/js-client-querying).

## Common configuration options

The client accepts several configuration options to customize its behavior. Here are the most commonly used options:

#### Properties

**projectId** (string, required)

Your Sanity project ID. You can find this at sanity.io/manage.

**dataset** (string, required)

The dataset name. Common values are production, staging, or development.

**useCdn** (boolean)

When set to true, queries use Sanity’s global CDN for faster response times and lower latency. Set to false when you need the freshest data or are performing mutations. Default is true.

**apiVersion** (string, required)

Specifies which version of the Sanity API to use. Set to a YYYY-MM-DD format. This ensures your application continues to work as expected when the API evolves. Learn more about API versions.

**token** (string)

An authentication token for accessing private datasets or performing mutations. You can create tokens in your project settings at sanity.io/manage.

Additional configuration options can be found in the [client reference documentation](https://reference.sanity.io/_sanity/client/index/ClientConfig/).

## Build on configuration with `withConfig`

You can extend the functionality of an existing client and change some values as needed with `withConfig`.

**sanity.ts**

```typescript
import {createClient} from '@sanity/client'

export const client = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'YOUR_DATASET',
  useCdn: false, // set to false when used with token
  apiVersion: '2026-03-01',
  token: process.env.SANITY_API_TOKEN,
})

export const draftClient = client.withConfig({
  perspective: 'drafts'
})

```

The `drafts` perspective needs a token with read access, because drafts aren’t visible to unauthenticated requests. `draftClient` inherits the `token` from `client`.

## Use within Studio

You can use the client within Studio components by importing [useClient](https://reference.sanity.io/sanity/index/useClient/). It comes pre-configured with settings passed down from the containing Studio components. Pass an `apiVersion`.

```typescript
import {useClient} from 'sanity'

export function MyComponent() {
  const client = useClient({apiVersion: '2026-03-01'})
  // ...use client to fetch or mutate content
  return null
}
```

## Environment-specific examples

The `@sanity/client` library works across different JavaScript environments. Here are examples for common setups:

**ESM (ES Modules)**

```javascript
import {createClient} from '@sanity/client'

const client = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'YOUR_DATASET',
  useCdn: true,
  apiVersion: '2026-03-01',
})

// Query for documents
const posts = await client.fetch('*[_type == "post"]')
console.log(posts)
```

**CommonJS**

```javascript
const {createClient} = require('@sanity/client')

const client = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'YOUR_DATASET',
  useCdn: true,
  apiVersion: '2026-03-01',
})

// Query for documents
client.fetch('*[_type == "post"]').then((posts) => {
  console.log(posts)
})
```

**TypeScript**

```typescript
import {createClient, type SanityClient} from '@sanity/client'

interface Post {
  _id: string
  _type: 'post'
  title: string
  slug: {current: string}
}

const client: SanityClient = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'YOUR_DATASET',
  useCdn: true,
  apiVersion: '2026-03-01',
})

// Query with type safety
const posts = await client.fetch<Post[]>('*[_type == "post"]')
console.log(posts)
```

**Next.js App Router**

```typescript
import {createClient} from '@sanity/client'

const client = createClient({
  projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
  dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
  useCdn: false, // Server components can use fresh data
  apiVersion: '2026-03-01',
})

export default async function Page() {
  const posts = await client.fetch('*[_type == "post"]')
  
  return (
    <div>
      {posts.map((post) => (
        <article key={post._id}>
          <h2>{post.title}</h2>
        </article>
      ))}
    </div>
  )
}
```

**Bun**

```javascript
import {createClient} from '@sanity/client'

const client = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'YOUR_DATASET',
  useCdn: true,
  apiVersion: '2026-03-01',
})

const posts = await client.fetch('*[_type == "post"]')
console.log(posts)
```

**Deno**

```typescript
import {createClient} from 'npm:@sanity/client'

const client = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'YOUR_DATASET',
  useCdn: true,
  apiVersion: '2026-03-01',
})

const posts = await client.fetch('*[_type == "post"]')
console.log(posts)
```

**Next.js Pages Router (Edge Runtime)**

```javascript
import {createClient} from '@sanity/client'

export const config = {
  runtime: 'edge',
}

const client = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'YOUR_DATASET',
  useCdn: true,
  apiVersion: '2026-03-01',
})

export default async function handler(request) {
  const posts = await client.fetch('*[_type == "post"]')
  return new Response(JSON.stringify(posts), {
    headers: {'content-type': 'application/json'},
  })
}
```

**Browser ESM CDN**

```html
<!DOCTYPE html>
<html>
<head>
  <title>Sanity Client Example</title>
</head>
<body>
  <div id="posts"></div>
  
  <script type="module">
    import {createClient} from 'https://esm.sh/@sanity/client@8'
    
    const client = createClient({
      projectId: 'YOUR_PROJECT_ID',
      dataset: 'YOUR_DATASET',
      useCdn: true,
      apiVersion: '2026-03-01',
    })
    
    const posts = await client.fetch('*[_type == "post"]')
    document.getElementById('posts').innerHTML = posts
      .map(post => `<h2>${post.title}</h2>`)
      .join('')
  </script>
</body>
</html>
```

`@sanity/client` v8 and later ship as ES modules only. `require()` still works on Node.js 22.12 or later through Node's built-in `require(esm)` support, but `import` is preferred.



## Related changelog entries

Entries are listed newest first; each link points to the full entry as markdown. Follow one when you need to know what changed, when, or why — for example, to summarize recent updates, explain behavior that differs from older documentation, or check whether a fix has shipped.

- [JavaScript Client v8.0.0: Node 22+ ESM-only support and refined upload, proxy, and error handling](https://www.sanity.io/docs/changelog/6c3650a7-8317-458f-bfa6-44c1ca4c9095.md) — August 12, 2026
- [JavaScript Client v3.0.0: Major version upgrade to the JavaScript Client (@sanity/client)](https://www.sanity.io/docs/changelog/2965cfa8-5fe4-4c52-b307-135e13116dc7.md) — August 12, 2022
- [Sanity Studio v2.21.10: Fixes for the pane and intent resolver](https://www.sanity.io/docs/changelog/95102907-cf0c-4190-a5ff-1f5e352d1204.md) — November 9, 2021