SR
Click to open github profile
Functions

getCraftQuery

Learn how to use the getCraftQuery function.


This function provides a simple way to fetch data from your Craft CMS Backend. It leverages the JS SDK to build query URLs and fetch for fetching data in server components.

Element Types

// query addresses
const { data, error } = await getCraftQuery('addresses').one()
// or use the shorthand
const { data, error } = await getCraftAddress().one()

// query assets
const { data, error } = await getCraftQuery('assets').one()
// or use the shorthand
const { data, error } = await getCraftAsset().one()

// query entry
const { data, error } = await getCraftQuery('entries').one()
// or use the shorthand
const { data, error } = await getCraftEntry().one()

// query users
const { data, error } = await getCraftQuery('users').one()
// or use the shorthand
const { data, error } = await getCraftUser().one()

Execute Query

The fetch request is executed by calling the .one() or .all() method. If you are only building the query object without executing it, you don't need to use await.

const query = getCraftQuery('entries').section('news')

// Fetch a single entry
const { data: singleEntry, error: singleError } = await query.one()

// Fetch all entries
const { data: allEntries, error: allError } = await query.all()

Available Methods

getCraftQuery supports all methods from js-craftcms-api.

Note

For the full list of available methods, see the documentation here.

In addition, the following methods are available for executing the query:

MethodDescriptionType
oneFetch one elementvoid
allFetch all elementsvoid

Example

// fetch without type definition
const { data, error } = await getCraftQuery('entries')
  .section('news')
  .fields(['title'])
  .limit(3)
  .all()

// with ts
type CraftEntry = {
  title: string
}
const { data, error } = await getCraftQuery<CraftEntry, 'entries'>('entries')
  .section('news')
  .fields(['title'])
  .limit(3)
  .all()

// or using the shorthand
const { data, error } = await getCraftEntry<CraftEntry>()
  .section('news')
  .fields(['title'])
  .limit(3)
  .all()

Types

type ElementType = 'addresses' | 'assets' | 'entries' | 'users'

export function getCraftQuery<ResT, T extends ElementType>(elementType: T): QueryBuilder<T> & {
  one(): Promise<{
    data: ResT | null;
    error: Error | null;
  }>;
  all(): Promise<{
    data: ResT | null;
    error: Error | null;
  }>;
}

Copyright © 2025 Samuel Reichör