@prismicio/client v6 Migration Guide

Overview

This is a guide for upgrading a project using @prismicio/client v5 to @prismicio/client v6.

@prismicio/client v6 includes a refreshed API and more flexibility in usage. The following instructions walk you through upgrading to the updated package.

Benefits of upgrading

  • ~25% smaller bundle size
  • More intuitive API names and options
  • New queryByType() and queryByTag() methods
  • Fetch all documents with getAll* queries
  • First-class TypeScript support

Update package in package.json

1. Update your package.json to use the latest version of @prismicio/client.

Copy
{
  "dependencies": {
    "@prismicio/client": "^6.0.0"
  }
}

Update your installed packages with npm.

Copy
npm install

Handling breaking changes

Replace default import with named import

Replace imports for @prismicio/client from a default import (usually Prismic) to a named export. As a convention, all code examples will use import * as prismic when importing @prismicio/client, but this can be modified depending on your preferences.

Copy

 import * as prismic from '@prismicio/client'

Create a client with createClient()

Replace all client creation methods with createClient(). All other methods of creating a client, including client(), getApi(), and api(), have been replaced by the single createClient() function.

Copy



 const client = prismic.createClient(endpoint)

createClient() accepts a Prismic Rest API V2 endpoint and an object with options. The endpoint string can be created using the new getEndpoint() function which ensures the API CDN is used for the best performance.

Copy
const endpoint = prismic.getEndpoint('my-repo-name')
const client = prismic.createClient(endpoint)

Provide a fetch() function if necessary

In environments where a global fetch() function is not available, such as Node.js, provide a fetch() function when creating a client. node-fetch is a popular server-side fetch() implementation that is compatible. This replaces the existing requestHandler option with a more browser-friendly and more Web API-compatible approach.

Copy
import * as prismic from '@prismicio/client'
import fetch from 'node-fetch'

const endpoint = prismic.getEndpoint('my-repo-name')
const client = prismic.createClient(endpoint, { fetch })

Environments like the browser, Next.js, Cloudflare Workers, and Remix provide a global fetch() function and do not require passing your own.

Replace network options with custom fetch() function

If your client requires custom network behavior, such as a proxy agent or a special cache, implement it using a custom fetch() function. A proxy agent, for example, can be implemented by using node-fetch and providing an agent option. A cache can be implemented by checking the URL for a cache hit before making a network request.

The exact migration steps will depend on your needs. You can perform any logic in the fetch() function provided that it returns a Response object containing the API response.

The following example integrates a custom cache:

Copy
import * as prismic from '@prismicio/client'
import fetch from 'node-fetch'
import QuickLRU from 'quick-lru'

const endpoint = prismic.getEndpoint('qwerty')
const cache = new QuickLRU({
  maxSize: 1000, // 1000 entries
})

const client = prismic.createClient(endpoint, {
  fetch: async (url, options) => {
    // The cache key contains the requested URL and headers
    const key = JSON.stringify({ url, options })

    if (cache.has(key)) {
      // If the cache contains a value for the key, return it
      return cache.get(key)
    } else {
      // Otherwise, make the network request
      const res = await fetch(url, options)

      if (res.ok) {
        // If the request was successful, save it to the cache
        cache.set(key, res)
      }

      return res
    }
  },
})

Enable auto previews in server contexts

If your client is used in a server context, such as in an Express app or Next.js API route, call the enableAutoPreviewsFromReq() method to enable automatic preview support. It must be passed a Request-like object, such as one from Express or Next.js.

Copy

 const client = prismic.createClient(endpoint)
 client.enableAutoPreviewsFromReq(req)

@prismicio/client v5 supported this feature by providing a req option when creating the client. The req option is replaced by the enableAutoPreviewsFromReq() method.

Replace query() with get()

Replace query() with get() by moving the query's predicates into a predicate option.

Copy




 const documents = client.get({
   predicates: prismic.predicate.at('document.tags', 'food'),
   lang: 'fr-fr',
 })

Replace Predicates with predicate

If your queries use predicates, replace Predicates with predicate. The predicate object contains the same predicate functions as Predicates with new names to better match the API's predicate names.

Copy

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


 prismic.predicate.numberGreaterThan('my.movie.rating', 3)

The following predicates have been renamed:

  • dayOfMonthdateDayOfMonth
  • dayOfMonthAfterdateDayOfMonthAfter
  • dayOfMonthBeforedateDayOfMonthBefore
  • dayOfWeekdateDayOfWeek
  • dayOfWeekAfterdateDayOfWeekAfter
  • dayOfWeekBeforedateDayOfWeekBefore
  • monthdateMonth
  • monthBeforedateMonthBefore
  • monthAfterdateMonthAfter
  • yeardateYear
  • hourdateHour
  • hourBeforedateHourBefore
  • hourAfterdateHourAfter
  • gtnumberGreaterThan
  • ltnumberLessThan
  • inRangenumberInRange
  • neargeopointNear

Replace previewCookie with cookie.preview

If you are using previewCookie, replace it with cookie.preview. The new import has the same value used to identify the Prismic preview cookie.

Replace getPreviewResolver() with resolvePreviewURL()

In your app's preview resolver page, replace getPreviewResolver() with resolvePreviewURL(). The previous getPreviewResolver() method returned an object with a resolve() method that returned a URL string.

resolvePreviewURL() simplifies this by directly returning the URL string. It also automatically reads the token and documentId URL parameters.

Copy







 const previewURL = await client.resolvePreviewURL({
   linkResolver,
   defaultURL: '/',
 })

If resolvePreviewURL() is used in an Express server-like environment, call enableAutoPreviewsFromReq() before calling resolvePreviewURL(). This will enable the client to automatically read the token and documentId URL parameters.

Copy
client.enableAutoPreviewsFromReq(req)
const previewURL = await client.resolvePreviewURL({
  linkResolver,
  defaultURL: '/',
})

If resolvePreviewURL() is used in a server environment without Express-like requests, provide the preview token and document ID manually using the previewToken and documentID parameters.

Copy
const previewURL = await client.resolvePreviewURL({
  linkResolver,
  defaultURL: '/',
  previewToken: 'example-preview-token',
  documentID: 'example-document-id',
})

Remove Experiment-related code

Prismic's Experiment feature is deprecated. As such, all Experiment-related APIs have been removed from the client. This includes the Experiments and experimentCookie exports.

Update TypeScript types

@prismicio/client v6 uses TypeScript types from @prismicio/types. While @prismcio/client v5 did not publicly export TypeScript types, its internal types were usable by importing directly from the package's files.

TypeScript is now a first-class citizen in @prismicio/client, but most types should be imported from @prismicio/types instead. Note that this package must be installed separately.

Copy
npm install --save-dev @prismicio/types

A document can be typed like this using @prismicio/types rather than an internal @prismicio/client type:

Copy

 import { PrismicDocument } from "@prismicio/types";


 const document: PrismicDocument = {
    id: 'abc123',
    // The rest of the document...
  }

New features

While migrating to @prismicio/client v6, you may also want to make use of new features included in the upgraded library.

The following steps are optional but recommended.

More query methods

Additional helpful query methods have been added that make querying content easier. This means you can spend less time figuring out query predicates.

The following new query methods are included:

  • getByType(): Query documents of a given type.
  • getByTag(): Query documents with a given tag.
  • getByEveryTag(): Query documents that have all tags from a given list of tags.
  • getBySomeTags(): Query documents that have at least one tag from a given list of tags.

See the @prismicio/client Technical Reference for a list of all query methods.

Query all documents with recursive query methods

By default, query methods return paginated responses with up to 100 documents. There are many cases where you need all documents for a query that might exceed the 100 document limit.

New getAll* methods are included for most query methods that automatically fetch each page of a query. The following example shows how you can query for all documents of a given type.

Copy
// If you have 300 Blog Post documents, this method will
// make multiple queries to fetch all Blog Posts.
const pages = await client.getAllByType('blog_post')

See the @prismicio/client Technical Reference for a list of all query methods.

Declaratively query content from Releases

Querying content from a Release in @prismicio/client v5 is a manual process. It requires fetching a Release's ref and setting it as a query option. @prismicio/client v6 allows you to query content from a Release whether you have its ID or only its label.

Copy
// If you have a Release's label
client.queryContentFromReleaseByLabel("My Release");

// Content is queried from "My Release"
const aboutPage = await client.getByUID("page", "about");

See the @prismicio/client Technical Reference for more details on the queryContentFrom* methods.

TypeScript

@prismicio/client is written in TypeScript with TypeScript users in mind. All components and hooks exported by the updated package include types so you will benefit without any changes to your code.

The package exports a collection of types that may be useful throughout your projects.

See the @prismicio/client TypeScript documentation for a list of the available types.


Can't find what you're looking for?

Need technical Support? Spot an error in the documentation? Get in touch with us on our Community Forum.