Fetch Data
In this article, you'll learn how to perform different queries to the Prismic API to get content in your Svelte application.
Before you proceed
First, you'll need a project with SvelteKit and Prismic. If you don't have one yet, start with the Install step.
For client-side fetching, call a Prismic query helper and assign the returned promise directly to a variable (do not wait for the promise to resolve). Then, use Svelte's built-in {#await} block to resolve the promise.
Here's what a basic query looks like:
<script>
import createClient from 'path/to/prismicClient' // Update the path
import * as prismicH from "@prismicio/helpers"
const client = createClient()
const prismicQuery = client.getFirst()
</script>
<h1>Prismic Svelte App</h1>
{#await prismicQuery}
<p>Loading...</p>
{:then document}
{@html prismicH.asHTML(document.data.example_title)}
{@html prismicH.asHTML(document.data.example_rich_text)}
{:catch error}
<p>Something went wrong:</p>
<pre>{error.message}</pre>
{/await}
There are two types of routes in SvelteKit: endpoints (.js files) and pages (.svelte files). To use data from the Prismic API, we will query the data in an endpoint and pass it to a corresponding page.
Endpoints are JavaScript modules. They export functions corresponding to an HTTP methods: get(), post(), put(), delete(). These functions allow your app to read and write data on a server, such as content from Prismic.
If you create an endpoint with the same path as a page component — such as /src/routes/[uid].js and /src/routes/[uid].svelte — the page component will receive data from the endpoint as a prop.
To access content from Prismic, you will create an endpoint with a get() function. The get() function should return a { status, headers, body } object that represents the response. Svelte will pass the properties of the body object to your component as props.
In your endpoint, import createClient(), create a client object, perform a query, and return the response:
//src/routes/[uid].js
import createClient from '$lib/prismicClient'
export async function get({ fetch, params }) {
const client = createClient(fetch)
const { uid } = params
const document = await client.getSingle('page', uid)
if (document) {
return {
body: { document }
}
}
return {
status: 404
}
}
The get() method receives a params object that includes a fetch() method as a property. You must pass the fetch() method to createClient(), since the Prismic client does not include its own fetching method.
Fetch a document from the Prismic API and return it from get() as body. The returned body properties will pass to the page component as props.
When an endpoint has the same filename as a page, the page will get receive its props from the endpoint. A page like src/routes/[uid].svelte could get its props from src/routes/[uid].js. To achieve this, initialize your props with export let in a <script> tag in the page component. Then the page component can access the props in the template.
In the following example, we have the endpoint route src/routes/[uid].js and the component route src/routes/[uid].svelte. This component will render for any route that matches the URL path /*. The uid — the first segment of the URL — will be available in the params parameter that is supplied to the get() function.
If you include a UID in your Custom Type, then you can query a document by its UID. For example, if a user visits /hello-world, you can then use the URL segment "hello-world" to query a document from Prismic with the UID hello-world.
Here's a full example, querying a document of type page by its UID. Here’s the endpoint:
//src/routes/[uid].js
import createClient from '$lib/prismicClient'
export async function get({ fetch, params }) {
const client = createClient(fetch)
const { uid } = params
const document = await client.getByUID('page', uid)
if (document) {
return {
body: { document }
}
}
return {
status: 404
}
}
And here’s the component:
<!-- src/routes/[uid].svelte -->
<script>
import * as PrismicH from '@prismicio/helpers'
export let document
</script>
<h1>{PrismicH.asText(document.data.title)}</h1>
getByUID(type, uid)
getByUID(type, uid, params)
Queries a document from the Prismic repository with a UID and Custom Type. type refers to the API ID of the Custom Type.
const document = await client.getByUID('post', 'my-first-post')
getSingle(type)
getSingle(type, params)
Queries a singleton document from the Prismic repository for a specific Custom Type. type refers to the API ID of the Custom Type.
For example, here we are querying for the only document of the Custom Type homepage.
const document = await client.getSingle('homepage')
getAllByType(type)
getAllByType(type, params)
Queries all documents from the Prismic repository for a specific Custom Type. type refers to the API ID of the Custom Type. This method may perform multiple network requests. It returns an array containing all matching documents from the repository.
const documents = await client.getAllByType('article')
Further Learning
There are many more methods for querying the API. All of these queries can accept params options to filter, sort, paginate and translate your query response. See them all in the @prismicio/client Technical Reference.
Here are a few common use cases.
In Prismic, you can create a singleton Custom Type to store site components, like a header, footer, nav menu, or SEO configuration.
To query a singleton, use the getSingle() method with the API ID of the singleton Custom Type.
//src/routes/index.js
import createClient from '$lib/prismicClient'
export async function get({ fetch }) {
const client = createClient(fetch)
const menu = await client.getSingle('menu')
return {
body: { menu }
}
}
On repeatable documents, we recommend adding a UID field — a unique identifier. Prismic formats each document's UID so it is URL-friendly and unique to its Custom Type.
To query a specific document of a given Custom Type, like a blog post, you can use the getByUID() method. To use getByUID(), pass the UID and the API ID of the Custom Type.
import createClient from '$lib/prismicClient'
export async function get({ fetch }) {
const client = createClient(fetch)
const document = await client.getByUID('page', 'hello-world')
return {
body: { document }
}
}
You will likely use getByUID() with a page's URL path to generate a page based on the URL. For instance, at /hello-world, you would want to display the document with the UID hello-world. Rather than hard-coding every page by its UID, in SvelteKit you can use dynamic URL parameters by putting the Svelte component's name in square brackets: src/routes/[uid].js. Then you can access the params and perform a query with it:
//src/routes/[uid].js
import createClient from '$lib/prismicClient'
export async function get({ fetch, params }) {
const client = createClient(fetch)
const { uid } = params
const document = await client.getByUID('page', uid)
return {
body: { document }
}
}
This will return a document dynamically, based on the URL, so you can template a repeatable document.
There are three ways to get all documents.
- You can query all documents of a certain type with getAllByType() (recommended).
- You can query a paginated list of all documents from your repository, regardless of type, using get(). This will return a paginated response, including the first 100 documents.
- To query an unpaginated list of all documents regardless of type, use dangerouslyGetAll(). Since the payload can be large, this method can cause performance issues, and it is not recommended.
//src/routes/index.js
import createClient from "$lib/prismicClient"
export async function get({ fetch }) {
const client = createClient(fetch)
const response = await client.getAllByType("page")
return {
body: { response }
}
}
Prismic allows you to publish your content in different languages. By default, the API will return content in your master language. To get content in a different language, add an options object with a lang option and a locale code. Here's an example of how to query the document of the type homepage in French (fr-fr).
//src/routes/index.js
import createClient from '$lib/prismicClient'
export async function get({ fetch }) {
const client = createClient(fetch)
const document = client.getSingle('homepage', { lang: 'fr-fr' })
return {
body: { document }
}
}
Was this article helpful?
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.