To save a query result globally at build time and make it available throughout your Astro project, you can use Astro's Content Collections API. This approach allows you to fetch the data once during the build process and use it across your site without querying on every page load. Here's how you can achieve this:
- First, create a content collection for your CSS variables. In your project, create a file at
src/content/config.ts (if it doesn't exist already) and add the following:
import { defineCollection, z } from 'astro:content';
const cssVariablesCollection = defineCollection({
type: 'data',
schema: z.object({
cssVariables: z.string()
})
});
export const collections = {
'cssVariables': cssVariablesCollection,
};
- Next, create a loader for this collection. In the same
src/content/config.ts file, modify the cssVariablesCollection to include a loader:
const cssVariablesCollection = defineCollection({
type: 'data',
schema: z.object({
cssVariables: z.string()
}),
loader: async () => {
const response = await fetch(`${import.meta.env.WORDPRESS_API_URL}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
query wpCssVariables {
cssVariables
}
`,
}),
});
const { data } = await response.json();
return [{ id: 'wordpress', cssVariables: data.cssVariables }];
}
});
- Now, you can access this data in any of your Astro components or pages using the
getEntry function from astro:content. Here's an example:
---
import { getEntry } from 'astro:content';
const cssVariablesEntry = await getEntry('cssVariables', 'wordpress');
const { cssVariables } = cssVariablesEntry.data;
---
<style set:html={cssVariables}></style>