@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.
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 functions.
Installation
npm install @prismicio/client@^6
Example
Here’s an example in Node.js (this example requires that you install node-fetch
).
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();
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 predicate functions.
- 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:
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 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
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.
prismic.getRepositoryName(repositoryEndpoint);
Get a repository’s API name based on a the Rest API or GraphQL API endpoint. Returns the name as a string.
This is useful for extracting a repository name from the sm.json
file.
prismic.createClient(endpoint);
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 functions are listed below.
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 field 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. |
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:
{
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.
Query filters
Filters are a way to refine your query, 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.
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.
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
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,
},
];
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 |
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
|
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.
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:
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 install 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.
TypeScript
@prismicio/client
is written in TypeScript and can be extended through type parameters. It is designed to work with types from the @prismicio/types
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.
# Install the codegen tool
npm install --save-dev prismic-ts-codegen @prismicio/types
# 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
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.
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.
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.
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.