@prismicio/client - v7
@prismicio/client
is the core Prismic package for creating web apps with Prismic and JavaScript. It is responsible for handling requests to your Prismic endpoint as well as providing a set of helpers and types to work with Prismic data.
Client, helpers, and types are all in one package now
Version 7 of @prismicio/client
includes content that was previously split between three different packages: @prismcio/client
, @prismicio/helpers
, and @prismicio/types
.
Since @prismicio/client
7, those packages were all merged together as the new @prismicio/client
to simplify the ecosystem. One package to install, one package to import from.
Are you on version 6 of @prismicio/client
? Follow our instructions to upgrade to version 7.
If you're using this library in an environment where a global fetch function does not exist, such as in Node.js 16 or earlier, you will need to provide such a function. For more information, see the section on setup functions.
This package works with the Prismic API V2. Most Prismic users are on V2 by default. You can tell if you're using V2 if your endpoint URL includes prismic.io/api/v2
.
- npm
- Yarn
npm install @prismicio/client
yarn add @prismicio/client
React Native setup
Using @prismicio/client
in React Native applications requires additional setup. See the Installation with React Native section for more details.
- Clean
- Commented
import * as prismic from '@prismicio/client'
import fetch from 'node-fetch'
const routes = [
{
type: 'page',
path: '/:uid',
},
]
const repoName = 'your-repo-name'
const client = prismic.createClient(repoName, { routes, fetch })
const init = async () => {
const pages = await client.getAllByType('page', {
orderings: {
field: 'document.first_publication_date',
direction: 'desc',
},
lang: 'en-us',
})
console.log(pages)
const firstPageDescriptionAsHTML = prismic.asHTML(pages[0].data.description)
}
init()
import * as prismic from '@prismicio/client'
import fetch from 'node-fetch'
const routes = [
// Define routes for your Custom Types.
{
type: 'page', // Documents of type 'page'
path: '/:uid', // will have this URL structure.
},
]
const repoName = 'your-repo-name' // Fill in with your repository name.
const client = prismic.createClient(repoName, { routes, fetch }) // Creates an API client object.
const init = async () => {
const pages = await client.getAllByType('page', {
// Fetches all documents of the given type.
orderings: {
// This option specifies how the results should be ordered.
field: 'document.first_publication_date', // Date the document was first published.
direction: 'desc', // In descending order.
},
lang: 'en-us', // Get the English version.
})
console.log(pages) // Will log an array of documents returned from the API.
const firstPageDescriptionAsHTML = prismic.asHTML(pages[0].data.description) // <p>This <em>should</em> return your formatted text.</p>
}
init()
@prismicio/client
provides tools for these uses:
- Setting up an API client in your project
- Constructing queries with query methods
- Filtering queries with query filters
- Get information about your repository with repository methods
- Manipulating your data with helpers
- Typing your data with types
- Migrating your content to Prismic with content migration helpers
The API client allows for querying Prismic Repository, Document, and Tags APIs.
All code snippets on this page assume that you have imported the package and set up a client, like so:
import * as prismic from '@prismicio/client'
const repoName = 'your-repo-name'
const client = prismic.createClient(repoName)
If your code runs in Node.js 16 or earlier (or another environment where a global fetch function is not available) you will need to import a fetch
function, as described in the section on setup functions. In environments where a global fetch function is available, like Next.js or the browser, you do not need to provide one.
Here are all of the @prismicio/client
's client functions:
prismic.createClient(repoName)
prismic.createClient(repoName, options)
Creates and returns a Prismic client object that can be used to query a repository. Accepts an optional object of API options.
The client object's methods are listed below in setup functions and repository methods.
The options object can have the following properties:
accessToken
string
The secure token for accessing the Prismic repository. This is only required if the repository is set to private.
ref
string
A ref identifier for the version of your content to query, which is generally either the master (latest) version or a draft version for previewing. This value is populated automatically, and most users will never need to touch it.
integrationFieldsRef
string
A ref identifier for the version of your Integration Fields content. This value is populated automatically, and most users will never need to touch it.
defaultParams
object
Default params that will be sent with each query. See the query params, below. These parameters can be overridden on each query.
fetch
function
The function used to make network requests to the Prismic API. In environments where a global fetch function does not exist, such as Node.js, this function must be provided.
routes
array
Defines the URL structure of your routes for the url property on each document in the API response. See the documentation on the Route Resolver for information on how to format the value.
Important: Providing a fetch function
The options object can include a fetch
property, to pass a fetching function. In environments where a global fetch
function does not exist, such as Node.js 16 or earlier, this function is required.
There are many libraries that can provide this function. The most common is node-fetch
, which you would configure like this:
import * as prismic from '@prismicio/client'
import fetch from 'node-fetch'
const repoName = 'your-repo-name'
const client = prismic.createClient(repoName, { fetch })
@prismicio/client
provides three main types of query methods: standard get methods, get-all methods, and get single methods.
Standard get methods — like get
, getByIDs
, getByType
, getByTag
, and getByEveryTag
— return a paginated API response. The default and maximum page size is 100 documents. The response includes pagination information and an array of document objects. The structure of the response looks like this:
{
page: 1,
results_size: 100,
total_results_size: 372,
total_pages: 4,
next_page: "https://...",
prev_page: null,
results: [
{...},
{...},
{...},
// ... 97 more items
]
}
Get-all methods — like getAllByIDs
, getAllByType
, getAllByTag
, getAllByEveryTag
, and dangerouslyGetAll
— perform a recursive query to fetch all matching documents from the API. These results are not paginated. They return only an array of document objects.
Note that the get-all methods are throttled. After the first request is sent, they wait at least 500ms before sending each subsequent request. This is meant to prevent issues on the API in case of large, complex queries. This will have no effect on queries returning fewer than 100 documents.
[
{...},
{...},
{...},
// ... 369 more items
]
Get single methods — like getFirst
, getByID
, getByUID
, and getSingle
— return only a single document object. The document object contains metadata and a data property, which contains the document's content:
{
id: "YLpzMxIAAFQztl0b",
uid: "hello-world",
type: "page",
first_publication_date: "2021-06-15T13:03:42+0000",
last_publication_date: "2021-08-26T12:23:35+0000",
lang: "en-us",
data: {...}
}
Here are all of the query methods:
client.get()
client.get(params)
client.get()
accepts an optional params object. It queries your repository based on the params object and returns a promise that resolves with the API response. If the params object is not provided, it will perform an unfiltered query. The API will return a maximum of 100 documents.
client.getFirst()
client.getFirst(params)
This is the same as client.get()
, but it only returns the first document.
client.getByID(id)
client.getByID(id, params)
Accepts a document ID as a string and an optional params object. Queries your Prismic repository for the document with the given ID. Returns a promise that resolves with the response.
client.getByIDs(arrayOfIDs)
client.getByIDs(arrayOfIDs, params)
Accepts an array of document ID strings and an optional params object. Queries your Prismic repository for the documents with the given IDs. Returns a promise that resolves with the API response. The API will return a maximum of 100 documents.
Documents will be returned in the order provided.
client.getAllByIDs(arrayOfIDs)
client.getAllByIDs(arrayOfIDs, params)
Accepts an array of document ID strings and an optional params object. Queries your Prismic repository for the documents with the given IDs. May perform multiple network requests. Returns a promise that resolves with an array containing all documents returned from the API.
Documents will be returned in the order provided.
client.getByUID(documentType, uid)
client.getByUID(documentType, uid, params)
Accepts a Custom Type API ID as a string, a UID as a string, and an optional params object. Queries your Prismic repository for the document of the given Custom Type with the given UID. Returns a promise that resolves with the API response.
client.getByUIDs(documentType, arrayOfUIDs)
client.getByUIDs(documentType, arrayOfUIDs, params)
Accepts a Custom Type API ID as a string, an array of document UID strings, and an optional params object. Queries your Prismic repository for the documents of the given Custom Type with the given UIDs. Returns a promise that resolves with the API response. The API will return a maximum of 100 documents.
Documents will be returned in the order provided.
client.getAllByUIDs(documentType, arrayOfUIDs)
client.getAllByUIDs(documentType, arrayOfUIDs, params)
Accepts a Custom Type API ID as a string, an array of document UID strings, and an optional params object. Queries your Prismic repository for the documents with the given UIDs. May perform multiple network requests. Returns a promise that resolves with an array containing all documents returned from the API.
Documents will be returned in the order provided.
client.getSingle(documentType)
client.getSingle(documentType, params)
Accepts the API ID for a singleton Custom Type and an optional params object. Queries your Prismic repository for the single document of the given Custom Type. Returns a promise that resolves with the API response.
client.getByType(documentType)
client.getByType(documentType, params)
Accepts the API ID of a Custom Type and an optional params object. Queries your Prismic repository for the documents of the given type. Returns a promise that resolves with the API response. The API will return a maximum of 100 documents.
client.getAllByType(documentType)
client.getAllByType(documentType, params)
Accepts the API ID of a Custom Type and an optional params object. Performs a recursive query to fetch all matching documents from your repo. To do so, it may perform multiple network requests. Returns a promise that resolves with an array of all documents returned from the API.
client.getByTag(tag)
client.getByTag(tag, params)
Accepts a Prismic tag as a string and an optional params object. Queries your Prismic repository for the documents with the given tag. Returns a promise that resolves with the API response. The API will return a maximum of 100 documents.
client.getAllByTag(tag)
client.getAllByTag(tag, params)
Accepts a Prismic tag as a string and an optional params object. Performs a recursive query to fetch all documents with the given tag from your repo. To do so, it may perform multiple network requests. Returns a promise that resolves with an array of all documents returned from the API.
client.getByEveryTag(arrayOfTags)
client.getByEveryTag(arrayOfTags, params)
Accepts an array of Prismic tags as strings and an optional params object. Queries your Prismic repository for documents that have all of the given tags. Returns a promise that resolves with the API response. The API will return a maximum of 100 documents.
client.getAllByEveryTag(arrayOfTags)
client.getAllByEveryTag(arrayOfTags, params)
Accepts an array of Prismic tags as strings and an optional params object. Performs a recursive query to fetch for all documents that have all of the given tags. To do so, it may perform multiple network requests. Returns a promise that resolves with an array of all documents returned from the API.
client.getBySomeTags(arrayOfTags)
client.getBySomeTags(arrayOfTags, params)
Accepts an array of Prismic tags as strings and an optional params object. Queries your Prismic repository for documents that have any of the given tags. Returns a promise that resolves with the API response. The API will return a maximum of 100 documents.
client.getAllBySomeTags(arrayOfTags)
client.getAllBySomeTags(arrayOfTags, params)
Accepts an array of Prismic tags as strings and an optional params object. Performs a recursive query to fetch for all documents that have any of the given tags. To do so, it may perform multiple network requests. Returns a promise that resolves with an array of all documents returned from the API.
client.dangerouslyGetAll()
client.dangerouslyGetAll(params)
Accepts an optional params object. Performs a recursive query to fetch all matching documents from your repo. To do so, it may perform multiple network requests. If the params object is not provided, it will query all documents in your repo. It returns a promise that resolves with an array containing all documents returned from the API.
We recommend caution when using dangerouslyGetAll()
. Querying all documents in your repository is not performant, and should only be used in unique cases.
Filters can be added to any query method. There are dozens of filters available with Prismic, allowing for powerful, flexible querying. @prismicio/client
provides a filter object to format your filters.
Here's an example of a query using filters. This query gets all documents of type 'blog-post' published in the year 2016.
import * as prismic from '@prismicio/client'
const repoName = 'your-repo-name'
const client = prismic.createClient(repoName)
const init = async () => {
client.get({
filters: [
prismic.filter.dateYear('document.last_publication_date', 2016),
prismic.filter.at('document.type', 'blog-post')
]
})
}
init()
Here are some of the most commonly-used filters. To learn how they work, see the filters section of the Documnent API documentation. (Filters are formerly called 'predicates.')
prismic.filter.at( path, value )
// filters for documents where the path matches a given value
prismic.filter.not( path, value )
// filters for documents where the path does not match a given value
prismic.filter.any( path, values )
// filters for documents where the path matches one item in a given array
prismic.filter.in( path, values )
// filters for document whose id or uid is in a given array
prismic.filter.numberLessThan( path, value )
// filters for documents where the path (a number field) is less than a given value
prismic.filter.numberGreaterThan( path, value )
// filters for documents where the path (a number field) is greater than a given value
client.getRepository()
Returns a promise that resolves with metadata about the Prismic repository, such as its refs, releases, and Custom Types.
client.getRefs()
Returns a promise that resolves with a list of all refs for the Prismic repository.
Here's an example output:
[
{
id: 'master',
ref: 'YTkRlxIAACEAT-Fo',
label: 'Master',
isMasterRef: true
}
]
What's a ref?
Refs are used to identify which version of the repository's content should be queried. All repositories will have at least one ref pointing to the latest published content called the master ref. For more information, read our intro to the Prismic API.
client.getRefByID(id)
Accepts an ID for a ref as a string. Return a promise that resolves with an object containing information about the specified ref.
client.getRefByLabel(label)
Accepts a label as a string. Return a promise that resolves with an object containing information about the specified ref.
client.getMasterRef()
Returns a promise that resolves with the master ref for the Prismic repository.
The master ref points to the repository's latest published content.
client.getReleases()
Returns a promise that resolves with a list of all Releases for the Prismic repository.
Releases are used to group content changes before publishing.
client.getReleaseByID(id)
Accepts the ID of a release as a string. Returns a promise that resolves with information about the specified release.
client.getReleaseByLabel(label)
Accepts the label of a release as a string. Returns a promise that resolves with information about the specified release.
client.getTags()
Returns a promise that resolves with a list of all tags in use in the repository.
client.resolvePreviewURL(params)
Accepts an object of parameters to determine the URL for a document to be previewed. Returns a promise that resolves with the URL as a string.
The parameters object can have the following properties:
linkResolver
function
A Link Resolver function to construct a URL. The Link Resolver is unnecessary if you are using the Route Resolver, and the Route Resolver will take precedence. See the docs on Link Resolving and Route Resolving.
defaultURL
string (required)
A fallback URL if neither the Link Resolver or Route Resolver return a value.
previewToken
string
The preview token (also known as a ref) that will be used to query preview content from the Prismic repository. If this parameter is not provided, the function will read the browser's URL or the server's request object (if provided by calling enableAutoPreviewsFromReq()
) to retrieve the token automatically.
documentID
string
The previewed document that will be used to determine the destination URL. If this parameter is not provided, the function will read the browser's URL or the server's request (if provided by calling enableAutoPreviewsFromReq()
) to retrieve the document ID automatically.
client.queryLatestContent()
Configures the client to query the latest published content. This is the client's default mode.
See an example with client.queryLatestContent()
in the package's GitHub repository.
client.queryContentFromReleaseByID(id)
Accepts the ID of a release as a string. Configures the client to query content from the specified release.
See an example with client.queryContentFromReleaseByID()
in the package's GitHub repository.
client.queryContentFromReleaseByLabel(label)
Accepts the label of a release as a string. Configures the client to query content from the specified release.
See an example with client.queryContentFromReleaseByLabel()
in the package's GitHub repository.
client.queryContentFromRef(ref)
Accepts a ref as a string. Configures the client to query content from the specified ref.
See an example with client.queryContentFromRef()
in the package's GitHub repository.
client.enableAutoPreviews()
Configures the client to automatically query content from a preview session. This is the client's default mode.
client.enableAutoPreviewsFromReq(req)
Accepts a server request object containing the request's headers and cookies. Configures the client to automatically query content from a preview session in a server environment.
client.disableAutoPreviews()
Configures the client to ignore preview sessions. Queries will be made against the latest published content or the client's configured release.
All of the query methods accept a params object. The params object can have the following properties:
filters
filter function | array
A filter is a search filter. The filters property takes a single filter function or an array of filter functions. If an array of filters is provided, the API will search for documents that match all filters.
orderings
object | array
The orderings property defines how to order your search results. It accepts an ordering object or an array of ordering objects. The ordering object has a field (which accepts a path) and an optional direction property (which can be either desc or asc and defaults to asc).
page
number
With the standard get methods, the API results are paginated. The page property defines what page of the API results to return, starting with and defaulting to 1.
pageSize
number
With the standard get methods, the API results are paginated. By default, the API returns 100 results per page. The pageSize property sets the results page size. It can be an integer from 1 to 100.
after
string
The after param tells the API to return all documents after a given document, specified by its ID.
accessToken
string
If your repository is private, your access token.
fetchLinks
string
The fetchLinks property tells the API to include data from a linked document. It takes the format [document-type].[field].
graphQuery
string
GraphQuery is an API option that allows deep fetching and selective fetching. Its syntax is similar to GraphQL. See more information in the Document API Technical Reference.
lang
string
A locale code to fetch content from a specific locale. Defaults to your master locale. Use * to get content from all locales.
routes
array
Defines the URL structure of your routes for the url property on each document in the API response. See the documentation on the Route Resolver for information on how to format the value.
We recommend defining your routes when you initialize your client, rather than when you perform a query.
These options are explained in detail in the Document API Technical Reference.
Here is an example query object:
const blogPosts = await client.getByType('blog-post', {
orderings: {
field: 'document.first_publication_date',
direction: 'desc',
},
fetchLinks: 'author.bio',
lang: 'fr-fr',
pageSize: 5,
page: 3,
})
In this example, getByType
queries the API for documents of type blog-post
. The params object specifies the following parameters:
- The
orderings
param determines that results will be descending by their first publication date. - The
fetchLinks
param tells the API to look for any linked documents of the type 'author' and include that document's 'bio' field in the response. - The
lang
param specifies what locale to query from. This defaults to the master locale. - The
pageSize
param specifies how many results to return per page of API results. It defaults to 20, and the max is 100. - The
page
param specifies what page of API results to return.
To demonstrate helper functions usage, we assume a Prismic document has already been queried and stored in a variable called document
.
prismic.asDate(field)
prismic.asDate()
accepts a Date or Timestamp field from Prismic (represented as a string) and converts it to a JavaScript Date object. To learn more about JavaScript Date objects, see the MDN Date documentation or this tutorial by Tania Rascia.
const date = prismic.asDate(document.data.example_date)
console.log(date.toISOString()) // '2018-01-16T13:46:15.000Z'
console.log(date.getFullYear()) // 2018
prismic.asLink(field)
prismic.asLink(field, config)
prismic.asLink()
accepts a Content Relationship field, a Link field, a Link to Media field, or a complete document from Prismic and returns its URL representation.
prismic.asLink(document.data.example_link)
// '/blog/peace-on-earth'
An optional Link Resolver function can be provided to the function as part of the config
parameter. A Link Resolver is only necessary if you are not using the Route Resolver. (See a comparison of the Link Resolver and Route Resolver)
const linkResolver = (doc) => {
if (doc.type === 'post') return `/blog/${doc.uid}/`
return `/${doc.uid}`
}
prismic.asLink(document.data.example_link, { linkResolver })
// '/blog/peace-on-earth'
prismic.asLinkAttrs(field)
prismic.asLinkAttrs(field, config)
prismic.asLinkAttrs()
accepts a Content Relationship field, a Link field, a Link to Media field, or a complete document from Prismic and returns its anchor attributes representation (href
and potential target
and rel
attributes).
prismic.asLinkAttrs(document.data.example_link)
// { href: '/blog/peace-on-earth', target: undefined, rel: undefined }
By default, prismic.asLinkAttrs()
will resolve the rel
attribute value to 'noreferrer'
for all external links. An optional rel
function can be provided as part of the config
parameter to fine-tune this behavior. It receives information about the resolved field and must return the desired rel
attribute value, if any.
const rel = ({ href, isExternal, target }) => {
return isExternal ? 'external' : 'opener'
}
prismic.asLinkAttrs(document.data.example_link, { rel })
// { href: '/blog/peace-on-earth', target: undefined, rel: 'opener' }
An optional Link Resolver function can be provided as part of the config
parameter to the function. A Link Resolver is only necessary if you are not using the Route Resolver. (See a comparison of the Link Resolver and Route Resolver)
const linkResolver = (doc) => {
if (doc.type === 'post') return `/blog/${doc.uid}/`
return `/${doc.uid}`
}
prismic.asLinkAttrs(document.data.example_link, { linkResolver })
// { href: '/blog/peace-on-earth', target: undefined, rel: undefined }
The rel
and linkResolver
configurations can be used alongside each other.
const rel = ({ href, isExternal, target }) => {
return isExternal ? 'external' : 'opener'
}
const linkResolver = (doc) => {
if (doc.type === 'post') return `/blog/${doc.uid}/`
return `/${doc.uid}`
}
prismic.asLinkAttrs(document.data.example_link, { rel, linkResolver })
// { href: '/blog/peace-on-earth', target: undefined, rel: 'opener' }
prismic.asHTML(field)
prismic.asHTML(field, config)
prismic.asHTML()
accepts a Rich Text or Title field from Prismic and returns its HTML representation as string.
prismic.asHTML(document.data.example_rich_text)
// '<p>This <em>should</em> return your formatted text.</p>'
An optional Link Resolver function can be provided as part of the config
parameter to the function to handle links in the text. It is only necessary if you are not using the Route Resolver.
const linkResolver = (doc) => {
if (doc.type === 'post') return `/blog/${doc.uid}/`
return `/${doc.uid}`
}
prismic.asHTML(document.data.example_rich_text, { linkResolver })
// '<p>This <em>should</em> return your formatted text.</p>'
prismic.asHTML()
uses a built-in Rich Text Serializer with sensible defaults to render Rich Text and Title fields as HTML. An optional serializer can be provided as part of the config
parameter to the function to selectively override these defaults. If the provided serializer returns null
for an element, the built-in serializer will handle that element.
const serializer = {
em: ({ children }) => `<strong>${children}</strong>`,
}
prismic.asHTML(document.data.example_rich_text, { serializer })
// '<p>This <strong>should</strong> return your formatted text.</p>'
The Link Resolver and custom Rich Text Serializer configurations can be used alongside each other.
const linkResolver = (doc) => {
if (doc.type === 'post') return `/blog/${doc.uid}/`
return `/${doc.uid}`
}
const serializer = {
em: ({ children }) => `<strong>${children}</strong>`,
}
prismic.asHTML(document.data.example_rich_text, { linkResolver, serializer })
// '<p>This <strong>should</strong> return your formatted text.</p>'
prismic.asText(field)
prismic.asText(field, config)
prismic.asText()
accepts a Rich Text or Title field from the Prismic API and converts it to a plain text string.
prismic.asText(document.data.example_rich_text)
// This should return your plain text.
An optional separator string can be provided as part of the config
parameter to join block-level elements. Its default value is ' '
a single whitespace.
prismic.asText(document.data.example_rich_text, { separator: '\n\n' })
// 'This should return your plain text
//
// with two carriage returns between paragraphs.'
prismic.asImageSrc(field)
prismic.asImageSrc(field, config)
prismic.asImageSrc()
accepts an Image field or one of its responsive views and returns its URL.
prismic.asImageSrc(document.data.example_image)
// https://images.prismic.io/repo/image.png?auto=format,compress
Image transformations, like resizing or cropping, can be applied by passing options to the config
parameter. Any of Imgix’s URL API parameters are supported (see Imgix’s URL API reference for a complete list).
In the following example, the sat: -100
parameter converts the image to grayscale by desaturating the image by 100%.
prismic.asImageSrc(document.data.example_image, { sat: -100 })
// https://images.prismic.io/repo/image.png?auto=format,compress&sat=-100
By default, all image URLs from Prismic apply the auto=format,compress
URL parameter to automatically optimize the image. This can be removed by setting the parameter to undefined
, like so:
prismic.asImageSrc(document.data.example_image, { auto: undefined })
// https://images.prismic.io/repo/image.png
If the Image field is empty, asImageSrc()
returns null
.
prismic.asImageSrc(document.data.empty_image)
// null
prismic.asImageWidthSrcSet(field)
prismic.asImageWidthSrcSet(field, config)
prismic.asImageWidthSrcSet()
accepts an Image field or one of its responsive views and returns an object containing its URL and a width-based srcset
attribute value. These values can be passed to <img>
or <source>
elements.
To learn more about srcset
and its variations, see MDN’s Responsive Images guide.
prismic.asImageWidthSrcSet(document.data.example_image)
// {
// src: 'https://images.prismic.io/repo/image.png',
// srcset: 'https://images.prismic.io/repo/image.png?width=640 640w, ' +
// 'https://images.prismic.io/repo/image.png?width=828 828w, ' +
// 'https://images.prismic.io/repo/image.png?width=1200 1200w, ' +
// 'https://images.prismic.io/repo/image.png?width=2048 2048w, ' +
// 'https://images.prismic.io/repo/image.png?width=3840 3840w'
// }
If the Image field contains responsive views, they will automatically be used for each item in the srcset
.
prismic.asImageWidthSrcSet(document.data.example_image)
// {
// src: 'https://images.prismic.io/repo/base.png',
// srcset: 'https://images.prismic.io/repo/base.png?width=2400 2400w, ' +
// 'https://images.prismic.io/repo/mobile.png?width=500 500w, ' +
// 'https://images.prismic.io/repo/tablet.png?width=650 650w, ' +
// 'https://images.prismic.io/repo/desktop.png?width=1200 1200w'
// }
If the Image field does not contain responsive views, the following widths will be used by default: 640w
, 828w
, 1200w
, 2048w
, 3840w
. To override the widths, provide a widths parameter.
prismic.asImageWidthSrcSet(document.data.example_image, {
widths: [200, 600],
})
// {
// src: 'https://images.prismic.io/repo/image.png',
// srcset: 'https://images.prismic.io/repo/image.png?width=200 200w, ' +
// 'https://images.prismic.io/repo/image.png?width=600 600w'
// }
Image transformations, like resizing or cropping, can be applied by passing options to the config
parameter. Any of Imgix’s URL API parameters are supported (see Imgix’s URL API reference for a complete list).
In the following example, the sat: -100
parameter converts the image to grayscale by desaturating the image by 100%.
prismic.asImageWidthSrcSet(document.data.example_image, { sat: -100 })
// {
// src: 'https://images.prismic.io/repo/image.png?sat=-100',
// srcset: 'https://images.prismic.io/repo/image.png?sat=-100&width=640 640w, ' +
// 'https://images.prismic.io/repo/image.png?sat=-100&width=828 828w, ' +
// 'https://images.prismic.io/repo/image.png?sat=-100&width=1200 1200w, ' +
// 'https://images.prismic.io/repo/image.png?sat=-100&width=2048 2048w, ' +
// 'https://images.prismic.io/repo/image.png?sat=-100&width=3840 3840w'
// }
If the Image field is empty, asImageWidthSrcSet()
returns null
.
prismic.asImageWidthSrcSet(document.data.empty_image)
// null
prismic.asImagePixelDensitySrcSet(field)
prismic.asImagePixelDensitySrcSet(field, config)
prismic.asImagePixelDensitySrcSet()
accepts an Image field or one of its responsive views and returns an object containing its URL and a pixel-density-based srcset
attribute value. These values can be passed to <img>
or <source>
elements.
To learn more about srcset
and its variations, see MDN’s Responsive Images guide.
prismic.asImagePixelDensitySrcSet(document.data.example_image)
// {
// src: 'https://images.prismic.io/repo/image.png',
// srcset: 'https://images.prismic.io/repo/image.png?dpr=1 1x, ' +
// 'https://images.prismic.io/repo/image.png?dpr=2 2x, ' +
// 'https://images.prismic.io/repo/image.png?dpr=3 3x'
// }
The following pixel densities will be used by default: 1x
, 2x
, 3x
. To override the pixel densities, provide a pixelDensities
parameter.
prismic.asImagePixelDensitySrcSet(document.data.example_image, {
pixelDensities: [2, 4],
})
// {
// src: 'https://images.prismic.io/repo/image.png',
// srcset: 'https://images.prismic.io/repo/image.png?dpr=2 2x, ' +
// 'https://images.prismic.io/repo/image.png?dpr=4 4x'
// }
Image transformations, like resizing or cropping, can be applied by passing options to the config
parameter. Any of Imgix’s URL API parameters are supported (see Imgix’s URL API reference for a complete list).
In the following example, the sat: -100
parameter converts the image to grayscale by desaturating the image by 100%.
prismic.asImagePixelDensitySrcSet(document.data.example_image, { sat: -100 })
// {
// src: 'https://images.prismic.io/repo/image.png?sat=-100',
// srcset: 'https://images.prismic.io/repo/image.png?sat=-100&dpr=1 1x, ' +
// 'https://images.prismic.io/repo/image.png?sat=-100&dpr=2 2x,' +
// 'https://images.prismic.io/repo/image.png?sat=-100&dpr=3 3x'
// }
If the Image field is empty, asImagePixelDensitySrcSet()
returns null
.
prismic.asImagePixelDensitySrcSet(document.data.empty_image)
// null
prismic.isFilled.color(field)
prismic.isFilled.contentRelationship(field)
prismic.isFilled.date(field)
prismic.isFilled.embed(field)
prismic.isFilled.geoPoint(field)
prismic.isFilled.image(field)
prismic.isFilled.imageThumbnail(field)
prismic.isFilled.integrationFields(field)
prismic.isFilled.keyText(field)
prismic.isFilled.link(field)
prismic.isFilled.linkToMedia(field)
prismic.isFilled.number(field)
prismic.isFilled.richText(field)
prismic.isFilled.select(field)
prismic.isFilled.timestamp(field)
prismic.isFilled.title(field)
prismic.isFilled.group(field)
prismic.isFilled.sliceZone(slices)
prismic.isFilled
is an object containing small functions that determine if a field has a value.
prismic.isFilled.link(document.data.example_link)
// `true` if `example_link` contains a link, `false` otherwise.
The isFilled
helpers can be used to display fallback content.
if (prismic.isFilled.title(document.data.example_title)) {
return `<h1>${document.data.example_title}</h1>`
} else {
return '<h1>Untitled</h1>'
}
A function is provided for each primitive field type:
color(field)
contentRelationship(field)
date(field)
embed(field)
geoPoint(field)
image(field)
imageThumbnail(field)
- A thumbnail within an Image field.integrationFields(field)
keyText(field)
link(field)
linkToMedia(field)
number(field)
richText(field)
select(field)
timestamp(field)
title(field)
A function is provided for each composite field type as well:
group(field)
- A Group field is filled if it contains at least one item.sliceZone(slices)
- A slice zone is filled if it contains at least one slice.
prismic.mapSliceZone(sliceZone, mappers)
prismic.mapSliceZone(sliceZone, mappers, context)
prismic.mapSliceZone()
converts slices from a slice zone into objects of your choosing. It is commonly used to add data, remove unused content, or process content on a server.
To use it, provide a slice zone and an object containing mapper functions, one for each type of slice to be modified.
// Add `myNewProperty` to the slice
prismic.mapSliceZone(document.data.slices, {
call_to_action: ({ slice }) => {
return { ...slice, myNewProperty: "myNewValue" }
}
})
The slice is replaced with the exact value returned by the mapper function. If you choose to return only a subset of the slice’s fields, only those fields will be included.
Mapper functions receive four arguments:
slice
: The original slice objectindex
: The index of the slice within the slice zoneslices
: The list of all slice objects in the slice zonecontext
: Arbitrary data passed tomapSliceZone()
's context argument
Mappers can be async, allowing you to fetch data or perform asynchronous processing.
// Run a syntax highlighter, like Shiki, on the server.
prismic.mapSliceZone(document.data.slices, {
code: ({ slice }) => {
return {
// Assume `highlight` adds syntax highlighting.
code: highlight(slice.primary.code)
}
}
})
mapSliceZone()
accepts a context
argument, which is arbitrary data that will be passed as an argument to each mapper function. This argument is helpful when mapper functions are defined in a different module where you do not have direct access to the data available around mapSliceZone()
.
// Query a document and one of its properties to a slice
const client = prismic.createClient('example-prismic-repo')
prismic.mapSliceZone(
document.data.slices,
{ call_to_action: callToActionMapper },
// Pass the client via the context object
{ client },
)
// In a different file, such as src/slices/CallToAction/mapper.ts
async function callToActionMapper({ slice, context }) {
const settings = await context.client.getSingle('settings')
return { ...slice, theme: settings.data.theme }
}
If a mapper is not provided for a slice type, the slice will not be modified.
When using the <SliceZone>
component from @prismicio/react
, @prismicio/vue
, or @prismicio/svelte
, properties returned by the mapper function become the slice component’s props. The following example shows how mapSliceZone()
can populate a React component’s slice
and lang
props.
// Pass `slice` and `lang` as a component props
prismic.mapSliceZone(document.data.slices, {
current_language: ({ slice }) => {
// The slice's component will be rendered like:
// <CurrentLanguage slice={slice} lang={document.lang} />
return { slice, lang: document.lang }
}
})
function CurrentLanguage({ slice, lang }) {
return <p>The current language is: {lang}</p>
}
You can migrate content to Prismic using a special write-capable version of the client. It uses the Asset API and Migration API.
Migrating to Prismic?
For a better understanding of how to work with the Asset API in the context of a migration, see the dedicated Migration article.
All code snippets in this section assume that you have imported the package and set up a write client like so:
import * as prismic from '@prismicio/client'
const repoName = 'your-repo-name'
const writeClient = prismic.createWriteClient(repoName, {
writeToken: process.env.PRISMIC_WRITE_TOKEN
})
This client works in environments supporting File
, Blob
, and FormData
, including Node.js 20 and later.
Here are all of the @prismicio/client
's write client functions:
prismic.createWriteClient(repoName, options)
Creates and returns a Prismic write client object that can be used to migrate content to a repository. This client requires a write token.
The options object can have the following properties:
writeToken
string
The secure token for writing to the Prismic repository. This mandatory token authenticates requests to Prismic write APIs.
migrationAPIKey
string
An optional Prismic Migration API key. If none is provided, the client will use a demo key.
assetAPIEndpoint
string
The Prismic Asset API endpoint. Defaults to the official endpoint: https://asset-api.prismic.io/
migrationAPIEndpoint
string
The Prismic Migration API endpoint. Defaults to the official endpoint: https://migration.prismic.io/
...clientOptions
Any other options supported by the regular client.
Only use the write client in secure environments
The write token is a secret that could be exposed in browser environments.
If you are not migrating content, prefer creating a regular, non-write client, with prismic.createClient()
.
writeClient.migrate(migration)
writeClient.migrate(migration, params)
writeClient.migrate()
migrates content to Prismic. It accepts a Migration
object containing the content to migrate.
The writeClient.migrate()
and your Prismic migration release can only handle up to 1,000 documents simultaneously. If you have more documents, we recommend batching them per locale when possible.
This method performs multiple network calls and can take some time to complete. To get visibility on where the process is at, provide a reporter
. The reporter
will receive events with relevant data.
await writeClient.migrate(migration, {
reporter: (event) => console.log(event)
})
A Migration
object is needed to call writeClient.migrate()
. It represents a set of content to migrate.
All code snippets in this section assume that you have imported the package and set up a Migration object like so:
import * as prismic from '@prismicio/client'
const migration = prismic.createMigration()
Here are all of the @prismicio/client
's migration functions:
prismic.createMigration()
Creates a Migration
object that can be used to query a repository.
migration.createDocument(document, title)
migration.createDocument(document, title, params)
migration.createDocument()
registers a document
to be created in the migration with a given title.
This method does not create the document in Prismic right away. Instead, it registers the document in your migration. The document will be created when the migration is executed through the writeClient.migrate()
method.
migration.createDocument()
returns a migration document object that can be used to define content relationships in migration documents.
const document = migration.createDocument(documentToCreate, title)
If an alternate language document should be associated to a master language document, it should be linked via the masterLanguageDocument
parameter.
migration.createDocument(document, title, {
// A Prismic document, a migration document,
// or a function returning one of them.
masterLanguageDocument: masterLanguageDocument
})
migration.updateDocument(document)
migration.updateDocument(document, title)
migration.updateDocument()
registers a document
to be updated in the migration.
This method does not update the document in Prismic right away. Instead, it registers the updated document in your migration. The document will be updated when the migration is executed through the writeClient.migrate()
method.
The document title displayed in the editor can also be updated.
migration.updateDocument(document, "New document title")
migration.updateDocument()
returns a migration document object that can be used to define content relationships in migration documents.
const document = migration.updateDocument(documentToUpdate)
migration.createDocumentFromPrismic(documentFromPrismic, title)
migration.createDocumentFromPrismic()
registers a document
from another Prismic repository to be created in the migration with a given title.
This method does not create the document in Prismic right away. Instead, it registers the document in your migration. The document will be created when the migration is executed through the writeClient.migrate()
method.
migration.createDocumentFromPrismic()
returns a migration document object that can be used to define content relationships in migration documents.
const document = migration.createDocumentFromPrismic(documentFromPrismic)
migration.createAsset(file, filename)
migration.createAsset(file, filename, params)
migration.createAsset()
registers an asset to be created in the migration from a file
with a given filename
.
This method does not create the asset in Prismic right away. Instead, it registers the asset in your migration. The asset will be created when the migration is executed through the writeClient.migrate()
method.
The file
parameter can be a URL string, a URL
object, a File
instance, or any value that accepted by File
in your environment (e.g. a Base 64 string, Blob
, etc.).
// URL-like
migration.createAsset('https://example.com/foo.png', 'foo.png')
migration.createAsset(new URL('https://example.com/bar.png'), 'bar.png')
// File-like
migration.createAsset(new File(['example-data']), 'baz.png')
migration.createAsset(fs.readFileSync('quux.png'), 'quux.png')
Metadata can be attached to the asset through the params
argument.
migration.createAsset(file, filename, {
notes: 'lorem',
credits: 'ipsum',
alt: 'dolor',
tags: ['sit', 'amet']
})
migration.createAsset()
returns a migration asset object that can be used to define image and link to media fields in migration documents.
const asset = migration.createAsset(file, filename);
const document = migration.createDocument({
data: { myImage: asset },
// ...
});
migration.getByUID(type, uid)
migration.getByUID()
queries a document from the migration object with a specific uid
and type
. It returns a migration document object if one is found. This method is useful for building lazy content relationships between documents in migration documents.
const fooDocument = migration.createDocument({
type: 'page',
uid: 'foo',
lang: 'en-us',
data: {
// `bar` does not exist yet in the migration,
// but we can already link to it.
related: () => migration.getByUID('page', 'bar')
}
}, 'Foo')
const barDocument = migration.createDocument({
type: 'page',
uid: 'bar',
lang: 'en-us',
data: {}
}, 'Bar')
migration.getSingle(type)
migration.getSingle()
queries a singleton document from the migration object with a specific type
. It returns a migration document object is one is found. This method is useful for building lazy content relationships between documents in migration documents.
const fooDocument = migration.createDocument({
type: 'page',
uid: 'foo',
lang: 'en-us',
data: {
// `bar` does not exist yet in the migration,
// but we can already link to it.
related: () => migration.getSingle('settings')
}
}, 'Foo')
const settingsDocument = migration.createDocument({
type: 'settings',
lang: 'en-us',
data: {}
}, 'Settings')
Using @prismicio/client
in React Native applications requires additional setup.
After installing @prismicio/client
, install the following URL Web API polyfill:
- npm
- Yarn
npm install react-native-url-polyfill
yarn add react-native-url-polyfill
Next, import the polyfill to your app’s entry file (typically this is App.js
or index.js
).
// App.js or index.js
import 'react-native-url-polyfill/auto'
@prismicio/client
can now be used throughout your app.
@prismicio/client
is written in TypeScript and can be extended through type parameters. It is designed to work with types from the same package, which includes types for fields, documents, and API responses.
We recommend using prismic-ts-codegen
in TypeScript and JavaScript projects to integrate types throughout your app’s code. The codegen command line tool converts your Prismic repository’s Custom Type and slice models to TypeScript types. It also automatically integrates the types into your @prismicio/client
instances.
# Install the codegen tool
npm install --save-dev prismic-ts-codegen
# Create a prismicCodegen.config.ts configuration file
npx prismic-ts-codegen init
# Generate types
npx prismic-ts-codegen
@prismicio/client
instances are automatically fully typed after running prismic-ts-codegen
.
import * as prismic from '@prismicio/client'
const client = prismic.createClient('your-repo-name')
// ^ Contains references to document types
const home = await client.getByUID('page', 'home')
// ^ Typed as PageDocument
Automatic TypeScript support
Learn more about automatic TypeScript support in the prismic-ts-codegen
Technical Reference.
@prismicio/client
and its query methods can be provided types to type their responses.
We recommend using prismic-ts-codegen
to generate TypeScript types for your Prismic content even when opting to manually provide types to @prismicio/client
instances. Using the code generator saves you from the task of manually writing types for your Custom Types and slices.
The following examples assume you have used prismic-ts-codegen
and saved generated types in a file called types.generated.ts
.
Providing types to createClient()
: A union of all document types can be provided to createClient()
. The client’s query methods will automatically be typed using the given types.
import * as prismic from '@prismicio/client'
import { AllDocumentTypes } from './types.generated'
const client = prismic.createClient<AllDocumentTypes>('your-repo-name')
// ^ Contains references to document types
const home = await client.getByUID('page', 'home')
// ^ Typed as PageDocument
If your project queries content from multiple Prismic repositories, you can use this type parameter to type individual clients with their own set of document types.
Providing types to query methods: Query methods accept a type parameter to define their return value’s type.
import * as prismic from '@prismicio/client'
import { PageDocument } from './types.generated'
const client = prismic.createClient('your-repo-name')
const home = await client.getByUID<PageDocument>('page', 'home')
// ^ Typed as PageDocument
This type parameter is useful if you only need to type a specific query or need to override an automatic type.
Content Relationship and Link fields allow querying for another document’s content using the graphQuery
or fetchLinks
query options. These queries are not automatically typed, but they can be defined in your app’s code.
In the following example, a Page document is queried with a fetchLinks
query option. The relatedBlogPost
's field value will include the selected Blog Post’s title
and description
fields within the data
property.
import * as prismic from '@prismicio/client'
import { BlogPostDocument } from './types.generated'
const client = prismic.createClient('your-repo-name')
// Typed as PageDocument
const home = await client.getByUID('page', 'home', {
fetchLinks: [
'my.relatedBlogPost.title',
'my.relatedBlogPost.description',
],
})
const relatedBlogPost = home.data.relatedBlogPost as typeof home.data.relatedBlogPost & {
data: Pick<BlogPostDocument['data'], 'title' | 'description'>
}
The relatedBlogPost
constant uses as
(TypeScript type assertion) to include the title
and description
properties.
Can't find what you're looking for?
Need technical Support? Spot an error in the documentation? Get in touch with us on our Community Forum.