Nuxt
In Nuxt, create the client once and fetch with useAsyncData, keyed by query.url().
Client setup
headquery init writes a client file next to the generated types. Generate
both into utils/ so Nuxt auto-imports cms everywhere:
npx headquery init --framework nuxt --out utils/cms.generated.ts # client: utils/cms.ts// utils/cms.ts
import { } from "@headquery/statamic";
import type { Schema } from "./cms.generated";
export const = <Schema>({
// To set it per environment, use runtimeConfig.public in nuxt.config and pass it in here.
: "https://cms.example.com",
});If your API needs a token, don’t put it in this shared client: code in utils/ also ends up
in the browser bundle. Read it from private runtimeConfig and use that client only in server
code, or keep the API public and read-only.
Fetching data
Use useAsyncData with query.url() as the key and .get() as the handler. The request runs
on the server during SSR, the result is sent to the client in the payload, and components that
build the same query share one entry because the key is the URL.
import { } from "nuxt/app"; // auto-imported in a Nuxt app
const = .("blog").("-date").(10).(["title", "slug", "date"]);
const { const data: Ref<Paginated<Pick<BlogEntry, "date" | "slug" | "title">> | undefined, Paginated<Pick<BlogEntry, "date" | "slug" | "title">> | undefined>data, , } = await (.(), (, { }) => .({ }));
Nuxt passes an AbortSignal to the handler; forwarding it to .get() cancels outdated requests.
Why not useFetch?
useFetch(query.url()) also works, because the URL is a complete, deterministic request:
import { } from "nuxt/app";
const = .("blog").("-date").(10);
const { } = await <<<typeof .>>>(.());But it bypasses the headquery client: the token, headers and fetchOptions from
createStatamicClient are not applied, errors are not HeadqueryHttpError, and the
result type has to be passed by hand. Prefer useAsyncData unless you specifically want
Nuxt’s $fetch.
Reactive queries
Build the query in a computed and pass getters for both the key and the handler. When the
query changes, its URL changes, and Nuxt fetches again:
import { } from "nuxt/app";
import { , } from "vue";
const = (1);
const = (() => .("blog").("-date").(10).(.));
const { } = await (
() => ..(),
(, { }) => ..({ }),
);
.++; // new URL → new requestNot found pages
Turn a 404 from the CMS into a Nuxt error page:
import { } from "@headquery/statamic";
import { , } from "nuxt/app";
const = .("blog").();
const { } = await (.(), async (, { }) => {
try {
return await .({ });
} catch () {
if ( instanceof && . === 404) {
throw ({ : 404, : "Post not found", : true });
}
throw ;
}
});