#Does using content collections make sense here?

4 messages · Page 1 of 1 (latest)

gaunt nymph
#

Hey there, so as part of the build scripts, I'm doing a fetch for the header and footer data once, and storing
it locally as a .json so that every single page that gets generated doesn't need to do a separate fetch request for the header and footer data..

It's my undrestnading that Astro has Content collectiosn for remote content that might be a better solution to this so the fetch
only happens once and is cached and shared across all pages that get built. Would this be the case?

toxic geodeBOT
#

Hi @gaunt nymph. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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:

// src/content.config.ts
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.

#

One thing to note: if your header/footer data changes very frequently and needs to be up-to-the-moment fresh on every request, a live collection would be more appropriate — but for mostly static layout data, a build-time collection is the right choice. [Types of collections]

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: