Sanity Library Reference Docs
    Preparing search index...

    -- Use import {SanityClient} from '@sanity/client' instead

    Hierarchy (View Summary)

    Index

    Constructors

    Properties - Configuration

    Properties - Releases

    Properties - Assets

    Properties - Agent Actions

    Properties - Real-time

    Properties - Projects & Datasets

    Properties - Other

    Methods - Configuration

    Methods - Querying

    Methods - Mutations

    Methods - Versions

    Methods - HTTP

    Constructors

    Properties - Configuration

    Observable version of the Sanity client, with the same configuration as the promise-based one

    Properties - Releases

    releases: {
        archive(
            params: { releaseId: string },
            options?: BaseActionOptions,
        ): Promise<SingleActionResult>;
        create(
            options: BaseActionOptions,
        ): Promise<
            SingleActionResult & {
                metadata: {
                    cardinality?: ReleaseCardinality;
                    description?: string;
                    intendedPublishAt?: string;
                    releaseType: ReleaseType;
                    title?: string;
                };
                releaseId: string;
            },
        >;
        create(
            release: {
                metadata?: Partial<
                    {
                        cardinality?: ReleaseCardinality;
                        description?: string;
                        intendedPublishAt?: string;
                        releaseType: ReleaseType;
                        title?: string;
                    },
                >;
                releaseId?: string;
            },
            options?: BaseActionOptions,
        ): Promise<
            SingleActionResult & {
                metadata: {
                    cardinality?: ReleaseCardinality;
                    description?: string;
                    intendedPublishAt?: string;
                    releaseType: ReleaseType;
                    title?: string;
                };
                releaseId: string;
            },
        >;
        delete(
            params: { releaseId: string },
            options?: BaseActionOptions,
        ): Promise<SingleActionResult>;
        edit(
            params: { patch: PatchOperations; releaseId: string },
            options?: BaseActionOptions,
        ): Promise<SingleActionResult>;
        fetchDocuments(
            params: { releaseId: string },
            options?: BaseMutationOptions,
        ): Promise<RawQueryResponse<SanityDocument[]>>;
        get(
            params: { releaseId: string },
            options?: { signal?: AbortSignal; tag?: string },
        ): Promise<ReleaseDocument | undefined>;
        publish(
            params: { releaseId: string },
            options?: BaseActionOptions,
        ): Promise<SingleActionResult>;
        schedule(
            params: { publishAt: string; releaseId: string },
            options?: BaseActionOptions,
        ): Promise<SingleActionResult>;
        unarchive(
            params: { releaseId: string },
            options?: BaseActionOptions,
        ): Promise<SingleActionResult>;
        unschedule(
            params: { releaseId: string },
            options?: BaseActionOptions,
        ): Promise<SingleActionResult>;
    }

    Create and manage content releases and their scheduled publishing

    Type declaration

    • archive: function
      • An archive action removes an active release. The documents that comprise the release are deleted and therefore no longer queryable.

        While the documents remain in retention the last version can still be accessed using document history endpoint.

        Parameters

        • params: { releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to archive.
        • Optionaloptions: BaseActionOptions

          Additional action options.

        Returns Promise<SingleActionResult>

        A promise that resolves to the transactionId.

    • create: function
      • Creates a new release under the given id, with metadata.

        Parameters

        • options: BaseActionOptions

          Additional action options.

        Returns Promise<
            SingleActionResult & {
                metadata: {
                    cardinality?: ReleaseCardinality;
                    description?: string;
                    intendedPublishAt?: string;
                    releaseType: ReleaseType;
                    title?: string;
                };
                releaseId: string;
            },
        >

        A promise that resolves to the transactionId and the release id and metadata.

        • If no releaseId is provided, a release id will be generated.
        • If no metadata is provided, then an undecided releaseType will be used.
        const releaseId = 'my-release'
        const releaseMetadata: ReleaseDocument['metadata'] = {
        releaseType: 'asap',
        }

        const result =
        await client.releases.create({releaseId, metadata: releaseMetadata})
        console.log(result)
        // {
        // transactionId: 'transaction-id',
        // releaseId: 'my-release',
        // metadata: {releaseType: 'asap'},
        // }
        const {metadata} = await client.releases.create()
        console.log(metadata.releaseType) // 'undecided'
        const {transactionId, metadata} = await client.releases.create({transactionId: 'my-transaction-id'})
        console.log(metadata.releaseType) // 'undecided'
        console.log(transactionId) // 'my-transaction-id'
      • Creates a new release under the given id, with metadata.

        Parameters

        • release: {
              metadata?: Partial<
                  {
                      cardinality?: ReleaseCardinality;
                      description?: string;
                      intendedPublishAt?: string;
                      releaseType: ReleaseType;
                      title?: string;
                  },
              >;
              releaseId?: string;
          }
        • Optionaloptions: BaseActionOptions

          Additional action options.

        Returns Promise<
            SingleActionResult & {
                metadata: {
                    cardinality?: ReleaseCardinality;
                    description?: string;
                    intendedPublishAt?: string;
                    releaseType: ReleaseType;
                    title?: string;
                };
                releaseId: string;
            },
        >

        A promise that resolves to the transactionId and the release id and metadata.

        • If no releaseId is provided, a release id will be generated.
        • If no metadata is provided, then an undecided releaseType will be used.
        const releaseId = 'my-release'
        const releaseMetadata: ReleaseDocument['metadata'] = {
        releaseType: 'asap',
        }

        const result =
        await client.releases.create({releaseId, metadata: releaseMetadata})
        console.log(result)
        // {
        // transactionId: 'transaction-id',
        // releaseId: 'my-release',
        // metadata: {releaseType: 'asap'},
        // }
        const {metadata} = await client.releases.create()
        console.log(metadata.releaseType) // 'undecided'
        const {transactionId, metadata} = await client.releases.create({transactionId: 'my-transaction-id'})
        console.log(metadata.releaseType) // 'undecided'
        console.log(transactionId) // 'my-transaction-id'
    • delete: function
      • A delete action removes a published or archived release. The backing system document will be removed from the dataset.

        Parameters

        • params: { releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to delete.
        • Optionaloptions: BaseActionOptions

          Additional action options.

        Returns Promise<SingleActionResult>

        A promise that resolves to the transactionId.

    • edit: function
      • Edits an existing release, updating the metadata.

        Parameters

        • params: { patch: PatchOperations; releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to edit.
          • patch - The patch operation to apply on the release metadata PatchMutationOperation.
        • Optionaloptions: BaseActionOptions

          Additional action options.

        Returns Promise<SingleActionResult>

        A promise that resolves to the transactionId.

    • fetchDocuments: function
      • Fetch the documents in a release by release id.

        Parameters

        • params: { releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to fetch documents for.
        • Optionaloptions: BaseMutationOptions

          Additional mutation options BaseMutationOptions.

        Returns Promise<RawQueryResponse<SanityDocument[]>>

        A promise that resolves to the documents in the release.

    • get: function
      • Retrieve a release by id.

        Parameters

        • params: { releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to retrieve.
        • Optionaloptions: { signal?: AbortSignal; tag?: string }

          Additional query options including abort signal and query tag.

        Returns Promise<ReleaseDocument | undefined>

        A promise that resolves to the release document ReleaseDocument.

        const release = await client.releases.get({releaseId: 'my-release'})
        console.log(release)
        // {
        // _id: '_.releases.my-release',
        // name: 'my-release'
        // _type: 'system.release',
        // metadata: {releaseType: 'asap'},
        // _createdAt: '2021-01-01T00:00:00.000Z',
        // ...
        // }
    • publish: function
      • Publishes all documents in a release at once. For larger releases the effect of the publish will be visible immediately when querying but the removal of the versions.<releasesId>.* documents and creation of the corresponding published documents with the new content may take some time.

        During this period both the source and target documents are locked and cannot be modified through any other means.

        Parameters

        • params: { releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to publish.
        • Optionaloptions: BaseActionOptions

          Additional action options.

        Returns Promise<SingleActionResult>

        A promise that resolves to the transactionId.

    • schedule: function
      • A schedule action queues a release for publishing at the given future time. The release is locked such that no documents in the release can be modified and no documents that it references can be deleted as this would make the publish fail. At the given time, the same logic as for the publish action is triggered.

        Parameters

        • params: { publishAt: string; releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to schedule.
          • publishAt - The serialised date and time to publish the release. If the publishAt is in the past, the release will be published immediately.
        • Optionaloptions: BaseActionOptions

          Additional action options.

        Returns Promise<SingleActionResult>

        A promise that resolves to the transactionId.

    • unarchive: function
      • An unarchive action restores an archived release and all documents with the content they had just prior to archiving.

        Parameters

        • params: { releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to unarchive.
        • Optionaloptions: BaseActionOptions

          Additional action options.

        Returns Promise<SingleActionResult>

        A promise that resolves to the transactionId.

    • unschedule: function
      • An unschedule action stops a release from being published. The documents in the release are considered unlocked and can be edited again. This may fail if another release is scheduled to be published after this one and has a reference to a document created by this one.

        Parameters

        • params: { releaseId: string }

          Release action parameters:

          • releaseId - The id of the release to unschedule.
        • Optionaloptions: BaseActionOptions

          Additional action options.

        Returns Promise<SingleActionResult>

        A promise that resolves to the transactionId.

    Properties - Assets

    assets: {
        upload(
            assetType: "file",
            body: UploadBody,
            options?: UploadClientConfig,
        ): Promise<SanityAssetDocument>;
        upload(
            assetType: "image",
            body: UploadBody,
            options?: UploadClientConfig,
        ): Promise<SanityImageAssetDocument>;
        upload(
            assetType: "file" | "image",
            body: UploadBody,
            options?: UploadClientConfig,
        ): Promise<SanityAssetDocument | SanityImageAssetDocument>;
    }

    Upload, fetch and delete assets (images and files) in the configured dataset

    Type declaration

    • upload: function
      • Uploads a file asset to the configured dataset

        Note: when the client is configured against a Media Library (resource: {type: 'media-library', id}), this resolves to a MediaLibraryAssetDocument at runtime, not to a SanityAssetDocument. The declared type cannot express that: the shape depends on the client's configuration rather than on the arguments, so an overload cannot discriminate it, and widening the return type into a union would be a breaking change for every existing caller. Narrow the result yourself (for example, check for currentVersion) if you upload to a Media Library. Typing this honestly is deferred to the next major.

        Parameters

        • assetType: "file"

          Asset type (file)

        • body: UploadBody

          Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.

        • Optionaloptions: UploadClientConfig

          Options to use for the upload

        Returns Promise<SanityAssetDocument>

      • Uploads an image asset to the configured dataset

        Note: against a Media Library this resolves to a MediaLibraryAssetDocument at runtime. See the 'file' overload above for why the declared type cannot say so.

        Parameters

        • assetType: "image"

          Asset type (image)

        • body: UploadBody

          Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.

        • Optionaloptions: UploadClientConfig

          Options to use for the upload

        Returns Promise<SanityImageAssetDocument>

      • Uploads a file or an image asset to the configured dataset

        Parameters

        • assetType: "file" | "image"

          Asset type (file/image)

        • body: UploadBody

          Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.

        • Optionaloptions: UploadClientConfig

          Options to use for the upload

        Returns Promise<SanityAssetDocument | SanityImageAssetDocument>

    mediaLibrary: {
        video: {
            getPlaybackInfo(
                assetIdentifier: MediaLibraryAssetInstanceIdentifier,
                options?: MediaLibraryPlaybackInfoOptions,
            ): Promise<
                VideoPlaybackInfo<
                    VideoPlaybackInfoItem,
                    VideoRenditionInfo,
                    VideoSubtitleInfo,
                >,
            >;
        };
    }

    Interact with Media Library assets

    Type declaration

    Properties - Agent Actions

    agent: {
        action: {
            generate<DocumentShape extends Record<string, any>>(
                request: GenerateInstruction<DocumentShape>,
            ): Promise<
                { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                    _type: string;
                } & DocumentShape,
            >;
            patch<DocumentShape extends Record<string, any>>(
                request: PatchDocument<DocumentShape>,
            ): Promise<
                { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                    _type: string;
                } & DocumentShape,
            >;
            prompt<const DocumentShape extends Record<string, any>>(
                request: PromptRequest<DocumentShape>,
            ): Promise<string>;
            transform<DocumentShape extends Record<string, any>>(
                request: TransformDocument<T>,
            ): Promise<
                { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                    _type: string;
                } & DocumentShape,
            >;
            translate<DocumentShape extends Record<string, any>>(
                request: TranslateDocument<T>,
            ): Promise<
                { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                    _type: string;
                } & DocumentShape,
            >;
        };
    }

    Run Agent Actions - AI-powered operations to generate, transform, translate, prompt and patch documents

    Type declaration

    • action: {
          generate<DocumentShape extends Record<string, any>>(
              request: GenerateInstruction<DocumentShape>,
          ): Promise<
              { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                  _type: string;
              } & DocumentShape,
          >;
          patch<DocumentShape extends Record<string, any>>(
              request: PatchDocument<DocumentShape>,
          ): Promise<
              { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                  _type: string;
              } & DocumentShape,
          >;
          prompt<const DocumentShape extends Record<string, any>>(
              request: PromptRequest<DocumentShape>,
          ): Promise<string>;
          transform<DocumentShape extends Record<string, any>>(
              request: TransformDocument<T>,
          ): Promise<
              { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                  _type: string;
              } & DocumentShape,
          >;
          translate<DocumentShape extends Record<string, any>>(
              request: TranslateDocument<T>,
          ): Promise<
              { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                  _type: string;
              } & DocumentShape,
          >;
      }

      Run individual Agent Action operations

      • generate: function
        • Run an instruction to generate content in a target document.

          Type Parameters

          • DocumentShape extends Record<string, any>

          Parameters

          Returns Promise<
              { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                  _type: string;
              } & DocumentShape,
          >

      • patch: function
        • Patch a document using a schema aware API. Does not use an LLM, but uses the schema to ensure paths and values matches the schema.

          Type Parameters

          • DocumentShape extends Record<string, any>

          Parameters

          Returns Promise<
              { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                  _type: string;
              } & DocumentShape,
          >

      • prompt: function
        • Run a raw instruction and return the result either as text or json

          Type Parameters

          • const DocumentShape extends Record<string, any>

          Parameters

          Returns Promise<string>

      • transform: function
        • Transform a target document based on a source.

          Type Parameters

          • DocumentShape extends Record<string, any>

          Parameters

          Returns Promise<
              { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                  _type: string;
              } & DocumentShape,
          >

      • translate: function
        • Translate a target document based on a source.

          Type Parameters

          • DocumentShape extends Record<string, any>

          Parameters

          Returns Promise<
              { [key: string]: any } & { _id: string } & { [key: string]: any } & {
                  _type: string;
              } & DocumentShape,
          >

    Properties - Real-time

    listen: {
        <
            R extends Record<string, any> = Record<string, any>,
            const G extends string = string,
        >(
            this: SanityClient | ObservableSanityClient,
            query: G,
            params?: ClientParams<G, ListenParams> | QueryWithoutParams,
        ): Observable<MutationEvent<R>>;
        <
            R extends Record<string, any> = Record<string, any>,
            Opts extends
                ListenOptions | ResumableListenOptions =
                | ListenOptions
                | ResumableListenOptions,
            const G extends string = string,
        >(
            this: SanityClient | ObservableSanityClient,
            query: G,
            params?: QueryWithoutParams | ClientParams<G, ListenParams>,
            options?: Opts,
        ): Observable<ListenEventFromOptions<R, Opts>>;
    } = _listen

    Listen to document changes matching a GROQ query, delivered as server-sent events

    Type declaration

    live: {
        events(
            __namedParameters?: {
                includeDrafts?: boolean;
                tag?: string;
                waitFor?: "function";
            },
        ): Observable<LiveEvent>;
    }

    Subscribe to live content updates through the Live Content API

    Type declaration

    • events: function
      • Requires apiVersion to be 2021-03-25 or later.

        Parameters

        • __namedParameters: { includeDrafts?: boolean; tag?: string; waitFor?: "function" } = {}
          • OptionalincludeDrafts?: boolean
          • Optionaltag?: string

            Optional request tag for the listener. Use to identify the request in logs.

            undefined

          • OptionalwaitFor?: "function"

            Delays events until after a Sanity Function has processed them and called the callback endpoint. When omitted, events are delivered immediately.

        Returns Observable<LiveEvent>

    Properties - Projects & Datasets

    datasets: {
        create(
            name: string,
            options?: DatasetCreateOptions,
        ): Promise<DatasetResponse>;
        delete(name: string): Promise<{ deleted: true }>;
        edit(name: string, options?: DatasetEditOptions): Promise<DatasetResponse>;
        editEmbeddingsSettings(
            name: string,
            settings: EmbeddingsSettingsBody,
        ): Promise<void>;
        getEmbeddingsSettings(name: string): Promise<EmbeddingsSettings>;
        list(): Promise<DatasetsResponse>;
    }

    Create, list, edit and delete datasets in the configured project

    Type declaration

    projects: {
        getById(projectId: string): Promise<SanityProject>;
        list<T extends ListOptions>(
            options?: T,
        ): Promise<Omit<SanityProject, OmittedProjectFields<T>>[]>;
    }

    Fetch information about the projects the authenticated user has access to

    Type declaration

    • getById: function
    • list: function
      • Fetch a list of projects the authenticated user has access to.

        Type Parameters

        • T extends ListOptions

        Parameters

        • Optionaloptions: T

          Options for the list request

          • includeMembers - Whether to include members in the response (default: true)
          • includeFeatures - Whether to include features in the response (default: true)
          • organizationId - ID of the organization to fetch projects for
          • onlyExplicitMembership - Whether to include only projects with explicit membership (default: false)

        Returns Promise<Omit<SanityProject, OmittedProjectFields<T>>[]>

    users: {
        getById<T extends string>(
            id: T,
        ): Promise<T extends "me" ? CurrentSanityUser : SanityUser>;
    }

    Fetch information about users in the configured project

    Type declaration

    Properties - Other

    collaboration: { comments: CollaborationCommentsClient }
    context: ContextClient
    functions: FunctionsClient

    Methods - Configuration

    Methods - Querying

    • Convenient and bandwidth efficient method of checking wether a set of document IDs exists. Returns a set of the IDs that exist.

      Parameters

      • ids: string[]

        Document IDs to check

      • Optionaloptions: { signal?: AbortSignal; tag?: string }

        Request options

      Returns Promise<Set<string>>

    • Fetch a single document with the given ID.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • id: string

        Document ID to fetch

      • options: {
            includeAllVersions: true;
            releaseId?: string;
            signal?: AbortSignal;
            tag?: string;
        }

        Request options

      Returns Promise<SanityDocument<R>[]>

    • Fetch a single document with the given ID.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • id: string

        Document ID to fetch

      • Optionaloptions: {
            includeAllVersions?: false;
            releaseId?: string;
            signal?: AbortSignal;
            tag?: string;
        }

        Request options

      Returns Promise<SanityDocument<R> | undefined>

    • Fetch multiple documents in one request. Should be used sparingly - performing a query is usually a better option. The order/position of documents is preserved based on the original array of IDs. If any of the documents are missing, they will be replaced by a null entry in the returned array

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • ids: string[]

        Document IDs to fetch

      • Optionaloptions: { signal?: AbortSignal; tag?: string }

        Request options

      Returns Promise<(SanityDocument<R> | null)[]>

    Methods - Mutations

    • Perform action operations against the configured dataset Returns a promise that resolves to the transaction result

      Parameters

      • operations: Action | Action[]

        Action operation(s) to execute

      • Optionaloptions: BaseActionOptions

        Action options

      Returns Promise<SingleActionResult | MultipleActionResult>

    • Create a document. Requires a _type property. If no _id is provided, it will be generated by the database. Returns a promise that resolves to the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • document: SanityDocumentStub<R>

        Document to create

      • options: FirstDocumentMutationOptions

        Mutation options

      Returns Promise<SanityDocument<R>>

    • Create a document. Requires a _type property. If no _id is provided, it will be generated by the database. Returns a promise that resolves to an array containing the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • document: SanityDocumentStub<R>

        Document to create

      • options: AllDocumentsMutationOptions

        Mutation options

      Returns Promise<SanityDocument<R>[]>

    • Create a document. Requires a _type property. If no _id is provided, it will be generated by the database. Returns a promise that resolves to a mutation result object containing the ID of the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • document: SanityDocumentStub<R>

        Document to create

      • options: FirstDocumentIdMutationOptions

        Mutation options

      Returns Promise<SingleMutationResult>

    • Create a document. Requires a _type property. If no _id is provided, it will be generated by the database. Returns a promise that resolves to a mutation result object containing the ID of the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • document: SanityDocumentStub<R>

        Document to create

      • options: AllDocumentIdsMutationOptions

        Mutation options

      Returns Promise<MultipleMutationResult>

    • Create a document. Requires a _type property. If no _id is provided, it will be generated by the database. Returns a promise that resolves to the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • document: SanityDocumentStub<R>

        Document to create

      • Optionaloptions: BaseMutationOptions

        Mutation options

      Returns Promise<SanityDocument<R>>

    • Create a document if no document with the same ID already exists. Returns a promise that resolves to the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<SanityDocument<R>>

    • Create a document if no document with the same ID already exists. Returns a promise that resolves to an array containing the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<SanityDocument<R>[]>

    • Create a document if no document with the same ID already exists. Returns a promise that resolves to a mutation result object containing the ID of the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<SingleMutationResult>

    • Create a document if no document with the same ID already exists. Returns a promise that resolves to a mutation result object containing the ID of the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<MultipleMutationResult>

    • Create a document if no document with the same ID already exists. Returns a promise that resolves to the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<SanityDocument<R>>

    • Create a document if it does not exist, or replace a document with the same document ID Returns a promise that resolves to the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<SanityDocument<R>>

    • Create a document if it does not exist, or replace a document with the same document ID Returns a promise that resolves to an array containing the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<SanityDocument<R>[]>

    • Create a document if it does not exist, or replace a document with the same document ID Returns a promise that resolves to a mutation result object containing the ID of the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<SingleMutationResult>

    • Create a document if it does not exist, or replace a document with the same document ID Returns a promise that resolves to a mutation result object containing the created document ID.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<MultipleMutationResult>

    • Create a document if it does not exist, or replace a document with the same document ID Returns a promise that resolves to the created document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      Returns Promise<SanityDocument<R>>

    • Deletes a document with the given document ID. Returns a promise that resolves to the deleted document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • id: string

        Document ID to delete

      • options: FirstDocumentMutationOptions

        Options for the mutation

      Returns Promise<SanityDocument<R>>

    • Deletes a document with the given document ID. Returns a promise that resolves to an array containing the deleted document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • id: string

        Document ID to delete

      • options: AllDocumentsMutationOptions

        Options for the mutation

      Returns Promise<SanityDocument<R>[]>

    • Deletes a document with the given document ID. Returns a promise that resolves to a mutation result object containing the deleted document ID.

      Parameters

      • id: string

        Document ID to delete

      • options: FirstDocumentIdMutationOptions

        Options for the mutation

      Returns Promise<SingleMutationResult>

    • Deletes a document with the given document ID. Returns a promise that resolves to a mutation result object containing the deleted document ID.

      Parameters

      • id: string

        Document ID to delete

      • options: AllDocumentIdsMutationOptions

        Options for the mutation

      Returns Promise<MultipleMutationResult>

    • Deletes a document with the given document ID. Returns a promise that resolves to a mutation result object containing the deleted document ID.

      Parameters

      • id: string

        Document ID to delete

      • Optionaloptions: BaseMutationOptions

        Options for the mutation

      Returns Promise<MultipleMutationResult>

    • Deletes one or more documents matching the given query or document ID. Returns a promise that resolves to first deleted document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • selection: MutationSelection

        An object with either an id or query key defining what to delete

      • options: FirstDocumentMutationOptions

        Options for the mutation

      Returns Promise<SanityDocument<R>>

    • Deletes one or more documents matching the given query or document ID. Returns a promise that resolves to an array containing the deleted documents.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • selection: MutationSelection

        An object with either an id or query key defining what to delete

      • options: AllDocumentsMutationOptions

        Options for the mutation

      Returns Promise<SanityDocument<R>[]>

    • Deletes one or more documents matching the given query or document ID. Returns a promise that resolves to a mutation result object containing the ID of the first deleted document.

      Parameters

      • selection: MutationSelection

        An object with either an id or query key defining what to delete

      • options: FirstDocumentIdMutationOptions

        Options for the mutation

      Returns Promise<SingleMutationResult>

    • Deletes one or more documents matching the given query or document ID. Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.

      Parameters

      • selection: MutationSelection

        An object with either an id or query key defining what to delete

      • options: AllDocumentIdsMutationOptions

        Options for the mutation

      Returns Promise<MultipleMutationResult>

    • Deletes one or more documents matching the given query or document ID. Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.

      Parameters

      • selection: MutationSelection

        An object with either an id or query key defining what to delete

      • Optionaloptions: BaseMutationOptions

        Options for the mutation

      Returns Promise<MultipleMutationResult>

    • Perform mutation operations against the configured dataset Returns a promise that resolves to the first mutated document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • operations: Mutation<R>[] | Patch | Transaction

        Mutation operations to execute

      • options: FirstDocumentMutationOptions

        Mutation options

      Returns Promise<SanityDocument<R>>

    • Perform mutation operations against the configured dataset. Returns a promise that resolves to an array of the mutated documents.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • operations: Patch | Transaction | Mutation<R>[]

        Mutation operations to execute

      • options: AllDocumentsMutationOptions

        Mutation options

      Returns Promise<SanityDocument<R>[]>

    • Perform mutation operations against the configured dataset Returns a promise that resolves to a mutation result object containing the document ID of the first mutated document.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • operations: Patch | Transaction | Mutation<R>[]

        Mutation operations to execute

      • options: FirstDocumentIdMutationOptions

        Mutation options

      Returns Promise<SingleMutationResult>

    • Perform mutation operations against the configured dataset Returns a promise that resolves to a mutation result object containing the mutated document IDs.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • operations: Patch | Transaction | Mutation<R>[]

        Mutation operations to execute

      • options: AllDocumentIdsMutationOptions

        Mutation options

      Returns Promise<MultipleMutationResult>

    • Perform mutation operations against the configured dataset Returns a promise that resolves to a mutation result object containing the mutated document IDs.

      Type Parameters

      • R extends Record<string, any> = Record<string, any>

      Parameters

      • operations: Patch | Transaction | Mutation<R>[]

        Mutation operations to execute

      • Optionaloptions: BaseMutationOptions

        Mutation options

      Returns Promise<MultipleMutationResult>

    • Create a new buildable patch of operations to perform

      Parameters

      • documentId: string

        Document ID to patch

      • Optionaloperations: PatchOperations

        Optional object of patch operations to initialize the patch instance with

      Returns Patch

      Patch instance - call .commit() to perform the operations defined

    • Create a new buildable patch of operations to perform

      Parameters

      • documentIds: string[]

        Array of document IDs to patch

      • Optionaloperations: PatchOperations

        Optional object of patch operations to initialize the patch instance with

      Returns Patch

      Patch instance - call .commit() to perform the operations defined

    • Create a new buildable patch of operations to perform

      Parameters

      • selection: MutationSelection

        An object with query and optional params, defining which document(s) to patch

      • Optionaloperations: PatchOperations

        Optional object of patch operations to initialize the patch instance with

      Returns Patch

      Patch instance - call .commit() to perform the operations defined

    Methods - Versions

    • Creates a new version of a published document.

      Type Parameters

      • R extends Record<string, any>

      Parameters

      • args: { document: SanityDocumentStub<R>; publishedId: string; releaseId?: string }
      • Optionaloptions: BaseActionOptions

        Additional action options.

      Returns Promise<SingleActionResult | MultipleActionResult>

      A promise that resolves to the transactionId.

      • The preferred approach is to use baseId to refer to the existing published document, but it is also possible to provide a complete document instead.
      • If document is provided, it must have a _type property.
      • Creating a version with no releaseId will create a new draft version of the published document.
      • If the document._id is defined, it should be a draft or release version ID that matches the version ID generated from publishedId and releaseId.
      • If the document._id is not defined, it will be generated from publishedId and releaseId.
      • To create a version of an unpublished document, use the client.create method.
      const transactionId = await client.createVersion({
      baseId: 'myDocument',
      publishedId: 'myDocument',
      releaseId: 'myRelease',
      })

      // The following document will be created:
      // {
      // _id: 'versions.myRelease.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
      const transactionId = await client.createVersion({
      baseId: 'myDocument',
      publishedId: 'myDocument',
      })

      // The following document will be created:
      // {
      // _id: 'drafts.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
    • Creates a new version of a published document.

      Type Parameters

      • R extends Record<string, any>

      Parameters

      • args: {
            document: IdentifiedSanityDocumentStub<R>;
            publishedId?: string;
            releaseId?: string;
        }
      • Optionaloptions: BaseActionOptions

        Additional action options.

      Returns Promise<SingleActionResult | MultipleActionResult>

      A promise that resolves to the transactionId.

      • The preferred approach is to use baseId to refer to the existing published document, but it is also possible to provide a complete document instead.
      • If document is provided, it must have a _type property.
      • Creating a version with no releaseId will create a new draft version of the published document.
      • If the document._id is defined, it should be a draft or release version ID that matches the version ID generated from publishedId and releaseId.
      • If the document._id is not defined, it will be generated from publishedId and releaseId.
      • To create a version of an unpublished document, use the client.create method.
      const transactionId = await client.createVersion({
      baseId: 'myDocument',
      publishedId: 'myDocument',
      releaseId: 'myRelease',
      })

      // The following document will be created:
      // {
      // _id: 'versions.myRelease.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
      const transactionId = await client.createVersion({
      baseId: 'myDocument',
      publishedId: 'myDocument',
      })

      // The following document will be created:
      // {
      // _id: 'drafts.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
    • Creates a new version of a published document.

      Parameters

      • args: {
            baseId: string;
            ifBaseRevisionId?: string;
            publishedId: string;
            releaseId?: string;
        }
      • Optionaloptions: BaseActionOptions

        Additional action options.

      Returns Promise<SingleActionResult | MultipleActionResult>

      A promise that resolves to the transactionId.

      • The preferred approach is to use baseId to refer to the existing published document, but it is also possible to provide a complete document instead.
      • If document is provided, it must have a _type property.
      • Creating a version with no releaseId will create a new draft version of the published document.
      • If the document._id is defined, it should be a draft or release version ID that matches the version ID generated from publishedId and releaseId.
      • If the document._id is not defined, it will be generated from publishedId and releaseId.
      • To create a version of an unpublished document, use the client.create method.
      const transactionId = await client.createVersion({
      baseId: 'myDocument',
      publishedId: 'myDocument',
      releaseId: 'myRelease',
      })

      // The following document will be created:
      // {
      // _id: 'versions.myRelease.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
      const transactionId = await client.createVersion({
      baseId: 'myDocument',
      publishedId: 'myDocument',
      })

      // The following document will be created:
      // {
      // _id: 'drafts.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
    • Deletes the draft or release version of a document.

      Parameters

      • params: { publishedId: string; releaseId?: string }

        Version action parameters:

        • releaseId - The ID of the release to discard the document from.
        • publishedId - The published ID of the document to discard.
      • Optionalpurge: boolean

        if true the document history is also discarded.

      • Optionaloptions: BaseActionOptions

        Additional action options.

      Returns Promise<SingleActionResult | MultipleActionResult>

      a promise that resolves to the transactionId.

      • Discarding a version with no releaseId will discard the draft version of the published document.
      • If the draft or release version does not exist, any error will throw.
      client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
      // The document with the ID `versions.myRelease.myDocument` will be discarded.
      client.discardVersion({publishedId: 'myDocument'})
      // The document with the ID `drafts.myDocument` will be discarded.
    • Replaces an existing version document.

      Type Parameters

      • R extends Record<string, any>

      Parameters

      • args: { document: SanityDocumentStub<R>; publishedId: string; releaseId?: string }
      • Optionaloptions: BaseActionOptions

        Additional action options.

      Returns Promise<SingleActionResult | MultipleActionResult>

      a promise that resolves to the transactionId.

      • Requires a document with a _type property.
      • If the document._id is defined, it should be a draft or release version ID that matches the version ID generated from publishedId and releaseId.
      • If the document._id is not defined, it will be generated from publishedId and releaseId.
      • Replacing a version with no releaseId will replace the draft version of the published document.
      • At least one of the version or published documents must exist.
      await client.replaceVersion({
      document: {_type: 'myDocument', title: 'My Document'},
      publishedId: 'myDocument',
      releaseId: 'myRelease',
      })

      // The following document will be patched:
      // {
      // _id: 'versions.myRelease.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
      await client.replaceVersion({
      document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},
      // `publishedId` and `releaseId` are not required since `document._id` has been specified
      })

      // The following document will be patched:
      // {
      // _id: 'versions.myRelease.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
      await client.replaceVersion({
      document: {_type: 'myDocument', title: 'My Document'},
      publishedId: 'myDocument',
      })

      // The following document will be patched:
      // {
      // _id: 'drafts.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
    • Replaces an existing version document.

      Type Parameters

      • R extends Record<string, any>

      Parameters

      • args: {
            document: IdentifiedSanityDocumentStub<R>;
            publishedId?: string;
            releaseId?: string;
        }
      • Optionaloptions: BaseActionOptions

        Additional action options.

      Returns Promise<SingleActionResult | MultipleActionResult>

      a promise that resolves to the transactionId.

      • Requires a document with a _type property.
      • If the document._id is defined, it should be a draft or release version ID that matches the version ID generated from publishedId and releaseId.
      • If the document._id is not defined, it will be generated from publishedId and releaseId.
      • Replacing a version with no releaseId will replace the draft version of the published document.
      • At least one of the version or published documents must exist.
      await client.replaceVersion({
      document: {_type: 'myDocument', title: 'My Document'},
      publishedId: 'myDocument',
      releaseId: 'myRelease',
      })

      // The following document will be patched:
      // {
      // _id: 'versions.myRelease.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
      await client.replaceVersion({
      document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},
      // `publishedId` and `releaseId` are not required since `document._id` has been specified
      })

      // The following document will be patched:
      // {
      // _id: 'versions.myRelease.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
      await client.replaceVersion({
      document: {_type: 'myDocument', title: 'My Document'},
      publishedId: 'myDocument',
      })

      // The following document will be patched:
      // {
      // _id: 'drafts.myDocument',
      // _type: 'myDocument',
      // title: 'My Document',
      // }
    • Used to indicate when a document within a release should be unpublished when the release is run.

      Parameters

      • params: { publishedId: string; releaseId: string }

        Version action parameters:

        • releaseId - The ID of the release to unpublish the document from.
        • publishedId - The published ID of the document to unpublish.
      • Optionaloptions: BaseActionOptions

        Additional action options.

      Returns Promise<SingleActionResult | MultipleActionResult>

      a promise that resolves to the transactionId.

      • If the published document does not exist, an error will be thrown.
      await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
      // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.

    Methods - HTTP

    • Get a Sanity API URL for the data operation and path provided

      Parameters

      • operation: string

        Data operation (eg query, mutate, listen or similar)

      • Optionalpath: string

        Path to append after the operation

      Returns string

    • Get a Sanity API URL for the URI provided

      Parameters

      • uri: string

        URI/path to build URL for

      • OptionalcanUseCdn: boolean

        Whether or not to allow using the API CDN for this route

      Returns string

    • Perform a request against the Sanity API NOTE: Only use this for Sanity API endpoints, not for your own APIs!

      Type Parameters

      • R = any

      Parameters

      • options: RawRequestOptions

        Request options

      Returns Promise<R>

      Promise resolving to the response body