What is @sanity/client?
@sanity/client is a JavaScript client for Sanity.io, a platform for structured content. It allows developers to interact with the Sanity content lake, enabling them to fetch, create, update, and delete documents, as well as perform queries and mutations.
What are @sanity/client's main functionalities?
Fetching Documents
This feature allows you to fetch documents from your Sanity dataset using GROQ queries. The example fetches all documents of type 'post'.
const sanityClient = require('@sanity/client');
const client = sanityClient({
projectId: 'yourProjectId',
dataset: 'yourDataset',
useCdn: true
});
client.fetch('*[_type == "post"]').then(posts => {
console.log(posts);
});
Creating Documents
This feature allows you to create new documents in your Sanity dataset. The example creates a new document of type 'post' with a title and body.
const sanityClient = require('@sanity/client');
const client = sanityClient({
projectId: 'yourProjectId',
dataset: 'yourDataset',
useCdn: false
});
client.create({
_type: 'post',
title: 'Hello World',
body: 'This is my first post!'
}).then(response => {
console.log('Document created:', response);
});
Updating Documents
This feature allows you to update existing documents in your Sanity dataset. The example updates the title of a document with a specific ID.
const sanityClient = require('@sanity/client');
const client = sanityClient({
projectId: 'yourProjectId',
dataset: 'yourDataset',
useCdn: false
});
client.patch('documentId')
.set({ title: 'Updated Title' })
.commit()
.then(updatedDocument => {
console.log('Document updated:', updatedDocument);
});
Deleting Documents
This feature allows you to delete documents from your Sanity dataset. The example deletes a document with a specific ID.
const sanityClient = require('@sanity/client');
const client = sanityClient({
projectId: 'yourProjectId',
dataset: 'yourDataset',
useCdn: false
});
client.delete('documentId').then(response => {
console.log('Document deleted:', response);
});
Other packages similar to @sanity/client
contentful
Contentful is a content management platform that provides a similar set of functionalities for managing structured content. It allows you to fetch, create, update, and delete content entries. Compared to @sanity/client, Contentful offers a more traditional CMS experience with a focus on ease of use and integration with various front-end frameworks.
prismic-javascript
Prismic is another headless CMS that offers a JavaScript client for interacting with its API. It provides functionalities for querying, creating, and managing content. Prismic's API is more RESTful compared to Sanity's GROQ-based querying, and it emphasizes a slice-based content modeling approach.
strapi-sdk-javascript
Strapi is an open-source headless CMS that provides a JavaScript SDK for interacting with its API. It allows you to perform CRUD operations on your content types. Strapi is highly customizable and can be self-hosted, offering more control over the backend compared to Sanity.
Sanity client
Javascript client for Sanity. Works in browsers (IE8+) and node.js.
Installation
The client can be installed from npm:
npm install --save @sanity/client
API
const sanityClient = require('@sanity/client')
const client = sanityClient({
projectId: 'your-project-id',
dataset: 'bikeshop',
token: 'sanity-auth-token'
})
const client = sanityClient(options)
Initializes a new Sanity Client. Required options are projectId
, dataset
and token
.
Performing queries
const query = 'bikeshop.bikes[.seats > 1] {.name, .seats}'
client.data.fetch(query).then(bikes => {
console.log('Bikes with more than one seat:')
bikes.forEach(bike => {
console.log(`${bike.name} (${bike.seats} seats)`)
})
})
client.data.fetch(query)
Perform a query using. Query string must be valid GQL syntax.
Creating documents
const doc = {name: 'Bengler Tandem Extraordinaire', seats: 2}
client.data.create(doc).then(res => {
console.log(`Bike was created, document ID is ${res.documentId}`)
})
client.data.create(doc)
Create a document. Parameter is a plain JS object representing the document.
Patch/update a document
client.data
.patch('bikeshop:bike-123')
.set({inStock: false})
.inc({numSold: 1})
.commit()
.then(() => {
console.log('Hurray, the bike is updated!')
})
.catch(err => {
console.error('Oh no, the update failed: ', err.message)
})
client.data.patch(docId).set(partialDoc).inc({key: value}).commit()
Modify a document. patch
takes a document ID. set
merges the partialDoc with the stored document. inc
increments the given field with the given numeric value. commit
executes the given patch
.
Delete a document
client.data.delete('bikeshop:bike-123')
.then(res => {
console.log('Bike deleted')
})
.catch(err => {
console.error('Delete failed: ', err.message)
})
client.data.delete(docId)
Delete a document. Parameter is a document ID.
Multiple mutations in a transaction
const namePatch = client.data
.patch('bikeshop:bike-310')
.set({name: 'A Bike To Go'})
client.data.transaction()
.create({name: 'Bengler Tandem Extraordinaire', seats: 2})
.delete('bikeshop:bike-123')
.patch(namePatch)
.commit()
.then(res => {
console.log('Whole lot of stuff just happened')
})
.catch(err => {
console.error('Transaction failed: ', err.message)
})
client.data.transaction().create(doc).delete(docId).patch(patch).commit()
Create a transaction to perform chained mutations.
client.data.transaction()
.create({name: 'Bengler Tandem Extraordinaire', seats: 2})
.patch('bikeshop:bike-123', p => p.set({inStock: false}))
.commit()
.then(res => {
console.log('Bike created and a different bike is updated')
})
.catch(err => {
console.error('Transaction failed: ', err.message)
})
client.data.transaction().create(doc).patch(docId, p => p.set(partialDoc)).commit()
A patch
can be performed inline on a transaction
.
Clientless patches & transactions
Transactions and patches can also be built outside the scope of a client:
const sanityClient = require('@sanity/client')
const client = sanityClient({
projectId: 'your-project-id',
dataset: 'bikeshop'
})
const patch = new sanityClient.Patch('<documentId>')
client.data.mutate(patch.inc({count: 1}).unset(['visits']))
const transaction = new sanityClient.Transaction()
.create({$id: 'foo:123', name: 'FooBike'})
.delete('foo:bar')
client.data.mutate(transaction)
const patch = new sanityClient.Patch(docId)
const transaction = new sanityClient.Transaction()
A few notes on this approach:
- You cannot call
commit()
on transactions or patches instantiated this way, instead you have to pass them to client.data.mutate()
- Documents passed to
create
, createIfMissing
and createOrReplace
needs to include an $id
property, since it cannot infer which dataset it should belong to. If you want Sanity to auto-generate one for you, set $id
to <datasetName:>
Get client configuration
const config = client.config()
console.log(config.dataset)
client.config()
Get client configuration.
Set client configuration
client.config({dataset: 'newDataset'})
client.config(options)
Set client configuration. Required options are projectId
, dataset
and token
.