@prismicio/client - v6

Overview

@prismicio/client is one of two fundamental Prismic packages for creating web apps with Prismic and JavaScript. It is primarily responsible for handling requests to your Prismic endpoint. The other is @prismicio/helpers, which helps to work with data from Prismic.

The package formerly known as 'prismic-javascript'

@prismicio/client used to be called prismic-javascript. The latter is now deprecated, and you can replace it with @prismicio/client.

Dependencies and requirements

If you're using this library in an environment where a global fetch function does not exist, such as Node.js, you will need to provide such a function. For more information, see the section on setup methods.

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 endpoint = prismic.getEndpoint(repoName)
const client = prismic.createClient(endpoint, { 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)
}

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 endpoint = prismic.getEndpoint(repoName); // Takes your repository name and converts it to an API endpoint.
const client = prismic.createClient(endpoint, { 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.
}

init();

Usage

@prismicio/client provides tools for four main uses:

  • Setting up an API client in your project.
  • Constructing standard queries with query methods.
  • Filtering queries with query predicates.
  • Get information about your repository with repository methods.

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 endpoint = prismic.getEndpoint(repoName);
const client = prismic.createClient(endpoint);

If your code runs in Node.js (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 methods. 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 methods:

Setup methods

Copy
prismic.getEndpoint(repoName)

Get a repository's Prismic Rest API V2 endpoint based on a repository name. Returns the repository's endpoint as a string.


Copy
prismic.createClient(endpoint[, 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 methods 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 Rest 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 method. In environments where a global fetch function does not exist, such as Node.js, 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 endpoint = prismic.getEndpoint("your-repo-name"); 
const client = prismic.createClient(endpoint, { 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([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([params])

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


Copy
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[, 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[, 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[, 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.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[, 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[, 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[, 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[, 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[, 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[, 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[, 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[, 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([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 predicates

Predicates are query filters, and they can be added to any query method. There are dozens of predicates available with Prismic, allowing for powerful, flexible querying. @prismicio/client provides a predicate object to format your predicates.

Here's an example of a query using predicates. This query gets all documents of type "blog-post" published in the year 2016.

Copy
import * as prismic from "@prismicio/client"

const endpoint = prismic.getEndpoint("your-repo-name")
const client = prismic.createClient(endpoint)

const init = async () => {
  client.get({ 
    predicates: [
      prismic.predicate.dateYear("document.last_publication_date", 2016),
      prismic.predicate.at("document.type", "blog-post")
    ]
  })
}

init()

Here are some of the most commonly-used predicates. To learn how they work, see the predicates documentation.

Copy
prismic.predicate.at( path, value )
// filters for documents where the path matches a given value

prismic.predicate.not( path, value )
// filters for documents where the path does not match a given value

prismic.predicate.any( path, values )
// filters for documents where the path matches one item in a given array

prismic.predicate.in( path, values )
// filters for document whose id or uid is in a given array

prismic.predicate.numberLessThan( path, value )
// filters for documents where the path (a number field) is less than a given value

prismic.predicate.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.


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.getReleasesByID(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.


Params object

All of the query helpers accept a params object. The params object can have the following properties:

predicates

predicate function | array

A predicate is a search filter. The predicates property takes a single predicate function or an array of predicate functions. If an array of predicates is provided, the API will search for documents that match all predicates.

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

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.


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.