@prismicio/client - v7

Overview

@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.

Dependencies and requirements

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.

Installation

  • npm
  • Yarn
npm
Copy
npm install @prismicio/client
Yarn
Copy
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.

Example

Here's an example in Node.js (this example requires that you install node-fetch).

  • Clean
  • Commented
Clean
Copy
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()
Commented
Copy
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()

Usage

@prismicio/client provides tools for six main 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

All code snippets on this page assume that you have imported the package and set up a client, like so:

Copy
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 functions:

Setup functions


Copy
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 })

Query methods

@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:

Copy
{
  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.

Copy
[
  {...},
  {...},
  {...},
  // ... 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:

Copy
{
  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:


Copy
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.


Copy
client.getFirst()
client.getFirst(params)

This is the same as client.get(), but it only returns the first document.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.

Query filters

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.

Copy
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.')

Copy
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

Repository methods

Copy
client.getRepository()

Returns a promise that resolves with metadata about the Prismic repository, such as its refs, releases, and Custom Types.


Copy
client.getRefs()

Returns a promise that resolves with a list of all refs for the Prismic repository.

Here's an example output:

Copy
[
  {
    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.


Copy
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.


Copy
client.getRefByLabel(label)

Accepts a label as a string. Return a promise that resolves with an object containing information about the specified ref.


Copy
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.


Copy
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.


Copy
client.getReleaseByID(id)

Accepts the ID of a release as a string. Returns a promise that resolves with information about the specified release.


Copy
client.getReleaseByLabel(label)

Accepts the label of a release as a string. Returns a promise that resolves with information about the specified release.


Copy
client.getTags()

Returns a promise that resolves with a list of all tags in use in the repository.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
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.


Copy
client.enableAutoPreviews()

Configures the client to automatically query content from a preview session. This is the client's default mode.


Copy
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.


Copy
client.disableAutoPreviews()

Configures the client to ignore preview sessions. Queries will be made against the latest published content or the client's configured release.


Query methods params

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:

Copy
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.

Helper functions

To demonstrate helper functions usage, we assume a Prismic document has already been queried and stored in a variable called document.

Copy
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.

Copy
const date = prismic.asDate(document.data.example_date)

console.log(date.toISOString()) // '2018-01-16T13:46:15.000Z'
console.log(date.getFullYear()) // 2018

Copy
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.

Copy
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)

Copy
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'

Copy
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).

Copy
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.

Copy
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)

Copy
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.

Copy
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' }

Copy
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.

Copy
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.

Copy
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.

Copy
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.

Copy
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>'

Copy
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.

Copy
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.

Copy
prismic.asText(document.data.example_rich_text, { separator: '\n\n' })
// 'This should return your plain text
//
// with two carriage returns between paragraphs.'

Copy
prismic.asImageSrc(field)
prismic.asImageSrc(field, config)

prismic.asImageSrc() accepts an Image field or one of its responsive views and returns its URL.

Copy
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%.

Copy
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:

Copy
prismic.asImageSrc(document.data.example_image, { auto: undefined })
// https://images.prismic.io/repo/image.png

If the Image field is empty, asImageSrc() returns null.

Copy
prismic.asImageSrc(document.data.empty_image)
// null

Copy
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.

Copy
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.

Copy
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.

Copy
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%.

Copy
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.

Copy
prismic.asImageWidthSrcSet(document.data.empty_image)
// null

Copy
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.

Copy
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.

Copy
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%.

Copy
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.

Copy
prismic.asImagePixelDensitySrcSet(document.data.empty_image)
// null

Copy
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.

Copy
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.

Copy
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.

Installation with React Native

Using @prismicio/client in React Native applications requires additional setup.

After installing @prismicio/client, install the following URL Web API polyfill:

  • npm
  • Yarn
npm
Copy
npm install react-native-url-polyfill
Yarn
Copy
yarn add react-native-url-polyfill

Next, import the polyfill to your app’s entry file (typically this is App.js or index.js).

Copy
// App.js or index.js

import 'react-native-url-polyfill/auto'

@prismicio/client can now be used throughout your app.

TypeScript

@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.

Automatic types

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.

Copy
# 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.

Copy
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.

Manual types

@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.

Copy
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.

Copy
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.

Typing Content Relationships

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.

Copy
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.


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.