Fetch Data

This technology has no Slice Machine integration

This framework has no integration with Prismic's developer tool, Slice Machine. You can still build a Prismic website with this technology by using Prismic's Legacy Builder. However, if you're starting a new project with Prismic, we strongly recommend using a technology that integrates with Slice Machine: Next.js or Nuxt.

This section will teach you how to connect to the API of your Prismic repository and how to create queries to retrieve documents.

Before your proceed

We strongly recommend building your app with a JavaScript framework, like Express, React, or Vue. If you choose to use vanilla JavaScript, you'll first need a project configured with Prismic. If you don't have one yet, start with the Setup step.

Define client options

The client object has methods for querying the Prismic API. If you haven't already, create a Prismic API client using the @prismicio/client package. createClient() creates a client object with your repository name.

createclient() accepts an optional access token (if your repository is private), a routes object to define the URL structure for each document's url property, and other options. See all available options in the @prismicio/client Technical Reference.

  • Node.js
  • Browser
Node.js
Copy
import * as prismic from '@prismicio/client'

const repositoryName = 'your-repository-name'
const accessToken = 'your-access-token' // Set an access token
const routes = [
  // Update to match your website's URL structure
  { type: 'page', path: '/:uid' },
  { type: 'home', path: '/' },
]

const client = prismic.createClient(repositoryName, { routes, accessToken })
Browser
Copy
import * as prismic from 'https://cdn.skypack.dev/@prismicio/client'

const repositoryName = 'your-repository-name'
const accessToken = 'your-access-token' // Set an access token
const routes = [
  // Update to match your website's URL structure
  { type: 'page', path: '/:uid' },
  { type: 'home', path: '/' },
]

const client = prismic.createClient(repositoryName, { routes, accessToken })

Update routes

You must update the routes array to match the custom types in your repository. If you name a custom type that does not exist in your repository, the API query will error.

From here you can start using client to create queries like the following one that retrieves a document of the singleton type "home":

Copy
const init = async () => {
  client.getSingle('home')
}

init()

Putting it all together, all queries will happen inside the init function:

  • Node.js
  • Browser
Node.js
Copy
import * as prismic from '@prismicio/client'

const repositoryName = 'your-repository-name'
const accessToken = 'your-access-token' // Set an access token
const routes = [
  // Update to match your website's URL structure
  { type: 'page', path: '/:uid' },
  { type: 'home', path: '/' },
]

const client = prismic.createClient(repositoryName, { routes, accessToken })

const init = async () => {
  /*
  All operations happen here
  */
}

init()
Browser
Copy
import * as prismic from 'https://cdn.skypack.dev/@prismicio/client'

const repositoryName = 'your-repository-name'
const accessToken = 'your-access-token' // Set an access token
const routes = [
  // Update to match your website's URL structure
  { type: 'page', path: '/:uid' },
  { type: 'home', path: '/' },
]

const client = prismic.createClient(repositoryName, { routes, accessToken })

const init = async () => {
  /*
  All operations happen here
  */
}

init()

The @prismicio/client kit offers query helper options to search for your documents.

Query methods

The query methods help you filter your documents. They are divided into three main categories:

  • paginated get methods
  • get-all methods
  • get-single methods

Further Learning

There are many more methods for querying the API. All of these queries can accept options to filter, sort, paginate, and translate your query response. See them all in the @prismicio/client Technical Reference.

Here are the most commonly-used query methods:

getByUID()

Accepts the UID of a document and an optional params object. Returns the document that matches the given custom type and UID.

Copy
client.getByUID(customType)
client.getByUID(customType, params)

For example, here we are querying for a page document with a UID of february-news.

Copy
const prismicDoc = await client.getByUID('page', 'february-news')

getSingle()

This method accepts a Single Custom Type API ID and an optional parameters object. It returns the document associated with the given Single type.

Copy
client.getSingle(customType)
client.getSingle(customType, params)

For example, here we are querying for the only document of the custom type home.

Copy
const prismicDoc = await client.getSingle('Home')

getFirst()

This method accepts an optional params object. It returns the first document that matches the search.

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

This example will return the most recent document from the repository:

Copy
const prismicDoc = await client.getFirst()

getAllByType()

This method accepts the API ID of a custom type, and an optional params object. It returns all the documents that match the custom type.

Copy
client.getAllByType(customType)
client.getAllByType(customType, params)

For example, here we are querying for all documents of the custom type blog_post.

Copy
const results = await client.getAllByType('blog_post')

getAllByIDs()

This method accepts an array of document ID strings and an optional params object. It returns all the documents that match the given IDs.

Copy
client.getAllByIDs(arrayOfIDs)
client.getAllByIDs(arrayOfIDs, params)

In the following example returns the documents that match the given IDs.

Copy
const results = await client.getAllByIDs(['WAjgAygAAN3B0a-a', 'WC7GECUAAHBHQd-Y'])

Params object

All of the query helper methods accept a params object. See the following usage examples.

accessToken

Accepts the access token for your repository, as a string. Is required if your repository is private.

Copy
{ accessToken: 'MC5ZVnRWUnhBQUFDWUE3N2tN.77...' }

fetchLinks

Retrieves content from a linked document. Formatted as '[custom-type].[field]'.

Copy
{ fetchLinks : 'author.first_name' }

lang

Accepts a locale code as a string or '*' to return all languages. Specifies what language to return. By default, the API will return content from the master locale.

Copy
{ lang: 'fr-fr' }

Learn more about the parameters object in the @prismicio/client Technical Reference.

filters

Filters are a way to refine your query. There are dozens of filters available with @prismicio/client.

Most filters follow the following pattern: [q] is a query filter, the path is a string that specifies the field being examined, and value specifies the value to evaluate against.

Copy
{
  filters: [prismic.filter.[q](path, value)]
}

Here are some examples of the most commonly-used filters.

at() filters for documents where the path matches a given value:

Copy
prismic.filter.at('my.product.category', 'shoes')

not() filters for documents where the path does not match a given value:

Copy
prismic.filter.not('my.product.category', 'shoes')

any() filters for documents where the path matches any value from an array:

Copy
prismic.filter.any('my.product.category', ['shoes', 'jackets', 'blouses'])

Read the complete filters documentation in the Rest API Technical Reference.

Usage examples

Here you'll find a list of common use cases that showcase how you can mix and match query methods, query options, and filters to make your queries as specific as you need.

Filter by a field

The my.[custom-type].[field] path allows you to query documents by specific fields: boolean, number, key text, select, group, and content relationship fields. You can use one or more filters in a single query.

Here is a basic filter by field:

Copy
client.getAllByType('product', {
  filters: [prismic.filter.at('my.product.category', 'shoes')]
})

Prismic also includes filters to filter by numbers and dates. This example will return all movies released in June 2022:

Copy
client.getAllByType('movie', {
  filters: [
    prismic.filter.month('my.movie.release-date', 'June'),
    prismic.filter.year('my.movie.release-date', 2022),
  ],
})

Filter by a content relationship

To query by a content relationship, use the ID of the linked document.

Copy
client.getAllByType('blog_post', {
  filters: [
    prismic.filter.at('my.blog_post.author_link', 'WNje3SUAAEGBu8bc'),
  ],
})

Filter by a field within a group

To query by a field within a group, prepend the API ID of the field with the API ID of the group, as in: [my.[custom-type].[group].[field].

This example shows a query by a content relationship inside a group, which is a useful use-case if you want to create your own tagging system (for example, to set "Authors" or "Categories" on each document).

Copy
client.getAllByType('blog_post', {
  filters: [
    prismic.filter.at(
      'my.blog_post.category_group.category_link',
      'WNje3SUAAEGBu8bc'
    ),
  ],
})

Query by a language

If you use more than one language in your repository, you'll need to query documents by language. If you don't specify a lang, the system will query the documents in your main language by default.

Copy
client.getAllByType('blog_post', { lang : 'fr-fr' })

Order results

Use an orderings object to sort your query results in a given order. The following example will sort blog posts by the date they were originally published, in descending order:

Copy
client.getAllByType('blog_post', {
  orderings: {
    field: 'document.first_publication_date',
    direction: 'desc',
  },
})

You can also specify an ordering by a field, or multiple fields:

Copy
client.getAllByType('product', {
  orderings: {
    field: 'my.product.price, my.product.title',
  },
})

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.