@prismicio/client Technical Reference

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 prismic-dom, which helps with rendering HTML.

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 & Requirements

This package works with the Prismic API V2. You can tell if you're using V2 if your endpoint URL includes prismic.io/api/v2.

To support legacy browsers, include a promise polyfill.

Installation

  • NPM
  • Yarn
Copy
npm install @prismicio/client
Copy
yarn install @prismicio/client

Example

Copy
const Prismic = require('@prismicio/client');
const apiEndpoint = 'https://your-repo-name.cdn.prismic.io/api/v2'
const client = Prismic.client(apiEndpoint, { req })

const init = async () => {
  const data = await client.query('')
  console.log(data)
}

init()

Usage

There are three categories of methods available in @prismicio/client:

  • API Setup: Methods for setting up an instance of the API in your project.
  • Query Helpers: Helper methods for querying the API, available on in a Client class.
  • Predicates: Predicate functions to format query predicates for the Prismic API.

This section assumes you have required @prismicio/client and stored it in a variable called Prismic, and created an instance of the Client class stored in a variable named client, like so:

Copy
const Prismic = require('@prismicio/client');
const apiEndpoint = 'https://your-repo-name.cdn.prismic.io/api/v2'
const client = Prismic.client(apiEndpoint, { req })

What is the req option?

When initializing your API in server-side apps, we recommend that you pass the req object as an option to Prismic.client(). This assigns a cookie to the req object, which enables Prismic to offer powerful functionalities, like unlimited different preview sessions. You can omit the req parameter if you're performing your queries client-side (eg: React, Vue).

Here are all of the @prismicio/client methods:

API Setup

Copy
Prismic.getApi(apiEndpoint, apiOptions)

Prismic.getApi() accepts your API endpoint and query options (optional) and queries apiEndpoint to access your API meta information (including your repo's refs, custom types, languages, tags). It returns a promise containing the response.

Copy
Prismic.client(apiEndpoint, apiOptions)

Prismic.client() accepts your API endpoint and query options (optional). It queries Prismic for your current ref, and returns an instance of the Prismic API client with that ref. (What's a ref?) The instance contains a collection of methods for querying (see below).

Query Helpers

Copy
client.query(query, options, callback)

client.query() accepts a query, query options (optional), and callback (optional). It queries your Prismic repo, and returns a promise containing the response.

The query can be:

Falsey: "", false, undefined, etc. Will return all documents.

A single predicate function: Prismic.Predicates.at('document.type', 'blog-post'). Will return all documents that match the predicate. A predicate is a query parameter. (More info.)

An array of predicate functions: [Prismic.Predicates.at('document.type', 'blog-post'), Prismic.Predicates.at('my.blog-post.tag','vacation')]. Will return all documents that match all predicates.


Copy
client.getApi()

Queries the API endpoint for API metadata and returns a promise containing the response.


Copy
client.getByID(id, options, callback)

Accepts a document ID, query options (optional), and a callback function (optional). Queries your Prismic repo for the document with the given ID. Returns a promise containing the response.


Copy
client.getByIDs(arrayOfIDs, options, callback)

Accepts an array of document IDs, query options (optional), and a callback function (optional). Queries your Prismic repo for the documents with the given IDs. Returns a promise containing the response.


Copy
client.getByUID(uid, type, options, callback)

Accepts a document UID, custom type API ID, query options (optional), and a callback function (optional). Queries your Prismic repo for the document of the given custom type with the given UID. Returns a promise containing the response.


Copy
client.getSingle(type, options, callback)

Accepts the API ID for a singleton custom type, query options (optional), and a callback function (optional). Queries your Prismic repo for the single document of the given custom type. Returns a promise containing the response.


Predicates

Simply put, a predicate is a query parameter. There are dozens of predicates available with Prismic, allowing for powerful, flexible querying. @prismicio/client provides a Predicate method to format your predicates for the client.query() method.

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

Copy
const Prismic = require('@prismicio/client') 
const apiEndpoint = 'https://your-repo-name.cdn.prismic.io/api/v2' 
const client = Prismic.client(apiEndpoint)

client.query([
  Prismic.Predicates.year('document.last_publication_date', 2016),
  Prismic.Predicates.at('document.type', 'blog-post')
])

Here are a few of the most commonly-used predicates. To learn more about how they work, please see the Predicate documentation.

Copy
Prismic.Predicates.at( path, value )
// checks for documents where the path matches a given value

Prismic.Predicates.not( path, value )
// checks for documents where the path does not match a given value

Prismic.Predicates.any( path, values )
// checks for documents where the path matches one item in a given array

Prismic.Predicates.in( path, values )
// checks for document whose id or uid is in a given array

Prismic.Predicates.lt( path, value )
// checks for documents where the path (a number field) is less than a given value

Prismic.Predicates.gt( path, value )
// checks for documents where the path (a number field) is greater than a given value

Query Options

The query() function and all query helpers can accept an options object as an argument. The options are explained in detail in the Rest API Technical Reference.

All query options are assigned as key–value pairs to an options object. They follow the same specifications as described in the Rest API documentation. Values should be unencoded and enclosed in quotation marks.

The available options are:

  • orderings
  • after
  • graphQuery
  • fetch
  • fetchLinks
  • lang
  • pageSize
  • page

Here is an example query object:

Copy
const Prismic = require('@prismicio/client')
const apiEndpoint = 'https://your-repo-name.cdn.prismic.io/api/v2'
const client = Prismic.client(apiEndpoint, { req })

const init = async () => {
  const data = await client.query('', {
    orderings: '[my.product.price desc, document.first_publication_date]',
    after: 'X47-TRIAACMAz8xC',
    fetch: ['product.title', 'product.price', 'product.image'],
    lang: 'fr-fr',
    pageSize: 100,
    page: 2
  })
  console.log(data)
}

init()

In this example, the query() method queries all documents in the repo — because the first argument is empty. The second argument is an options object, with the following options:

  • The orderings option takes an array of paths to determine the order of results. The API will results by the first path (the product's price, in descending order), and then by the document's first publication date.
  • The after option specifies that the API should return all documents that come after the document with the ID X47-TRIAACMAz8xC.
  • The fetch option specifies that the API should only return the requested fields: a product's title, price, and image.
  • The lang option specifies that the API should return the French version of the document.
  • pageSize tells the API to paginate the results in pages of 100 documents.
  • page option requests the second page of results.

Query Callbacks

After the options object, all query methods can also accept a callback function as a subsequent argument. The callback function receives the API response as its second argument.

Copy
const Prismic = require('@prismicio/client')
const apiEndpoint = 'https://your-repo-name.cdn.prismic.io/api/v2'
const client = Prismic.client(apiEndpoint, { req })

const init = () => {
  client.query(
    '', 
    { lang: 'fr-fr' },
    ( error, document ) => error ? console.log(error) : console.log(document)
  )
}

init()