Yes, using a build-time content collection makes a lot of sense for your use case and is a cleaner alternative to manually saving a .json file in your build scripts.
Here's why it fits:
- Build-time collections fetch data once at build time and store it in a persistent data layer (the content layer data store), which is shared across all pages generated during the build. [Types of collections]
- The data is cached between builds, so you get the same "fetch once, reuse everywhere" behavior you're currently implementing manually. [When to create a collection]
- You can use a custom build-time loader to fetch your remote header/footer data from any API endpoint, which replaces your manual fetch-and-save script. [Custom build-time loaders]
A minimal example of how this could look:
import { defineCollection } from 'astro:content';
import { myLoader } from './loader.ts';
const siteLayout = defineCollection({
loader: myLoader({
url: "<https://api.example.com/header-footer",>
apiKey: "my-secret",
}),
});
export const collections = { siteLayout };
Then in any page, you'd use getCollection('siteLayout') or getEntry('siteLayout', 'header') to access the data without triggering a new fetch. [Querying build-time collections]
This approach gives you type safety, editor autocomplete, and built-in caching — all without needing a custom build script to manage the .json file manually.