🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Content & MDX••By Komal Nakrani

Astro Live Collections: Fetch Content at Request Time

Astro live collections explained: define them in src/live.config.ts, write a live loader, query with getLiveCollection and getLiveEntry, handle errors and cache.

#Astro#Live Collections#Content Collections#Server Rendering#Loaders

Astro live collections are content collections that fetch their data on every request instead of at build time. You define them with defineLiveCollection() in src/live.config.ts, give each one a live loader, and query them with getLiveCollection() and getLiveEntry() from astro:content in on-demand rendered pages. Use them when data changes too often to rebuild for, such as stock levels, prices or newly published CMS entries.

Regular collections, defined in src/content.config.ts, load once during the build and are stored in Astro’s data store. Live collections skip that store. Each request calls the loader, which makes data always current, at the cost of a network call per page view.

Key Takeaways

  • Live collections live in src/live.config.ts; build-time collections stay in src/content.config.ts.
  • A live loader is an object with name, loadCollection() and loadEntry().
  • getLiveCollection() and getLiveEntry() return { entries, error } or { entry, error } rather than throwing.
  • Live collections only make sense on pages rendered on demand, which need an adapter.
  • Loaders can return cache hints (tags, last modified) that work with Astro’s route caching.

When to use live collections

Data Build-time collection Live collection
Blog posts, docs pages Best Unnecessary
Product descriptions Best, rebuild on change Possible
Prices and stock Stale between builds Best
CMS previews of drafts Needs a rebuild Best
Search results, user-specific data Not possible Possible, but an endpoint may fit better
Very large catalogues Slow builds Fetch only what is requested

If you can rebuild when content changes (a CMS webhook triggering a deploy), build-time collections are faster and cheaper: pages are static and the loader runs once. Choose live collections when a rebuild is too slow or too frequent. The content collections guide covers the build-time side.

Prerequisites

Live collections run in server code at request time, so the pages that use them must be rendered on demand:

  1. Install an adapter, for example npx astro add node.
  2. Either set output: 'server', or keep the default static output and add export const prerender = false to the pages that query live data.

The Astro SSR guide explains adapters, and mixing static and on-demand pages shows the per-page approach.

Define a live collection

Create src/live.config.ts. Astro requires live collections to be defined in this file; defining one in content.config.ts throws an error.

// src/live.config.ts
import { defineLiveCollection } from 'astro:content';
import { z } from 'astro/zod';
import { productLoader } from './loaders/products';

const products = defineLiveCollection({
  loader: productLoader({ apiUrl: 'https://api.example.com' }),
  schema: z.object({
    name: z.string(),
    price: z.number(),
    inStock: z.boolean(),
  }),
});

export const collections = { products };

The schema is optional. When present, Astro validates each entry the loader returns and reports a validation error instead of rendering bad data.

Write a live loader

A live loader is a plain object. loadCollection() returns a list of entries; loadEntry() returns one entry or undefined. Both receive a filter argument whose shape you define.

// src/loaders/products.ts
import type { LiveLoader } from 'astro/loaders';

interface Product {
  name: string;
  price: number;
  inStock: boolean;
}

interface EntryFilter { id: string }
interface CollectionFilter { category?: string }

export function productLoader(opts: { apiUrl: string }): LiveLoader<Product, EntryFilter, CollectionFilter> {
  return {
    name: 'product-loader',
    async loadCollection({ filter }) {
      try {
        const url = new URL('/products', opts.apiUrl);
        if (filter?.category) url.searchParams.set('category', filter.category);
        const res = await fetch(url);
        const items: Array<Product & { id: string }> = await res.json();
        return {
          entries: items.map(({ id, ...data }) => ({ id, data })),
          cacheHint: { tags: ['products'] },
        };
      } catch (error) {
        return { error: error as Error };
      }
    },
    async loadEntry({ filter }) {
      try {
        const res = await fetch(new URL(`/products/${filter.id}`, opts.apiUrl));
        if (res.status === 404) return undefined;
        const { id, updatedAt, ...data } = await res.json();
        return {
          id,
          data,
          cacheHint: { tags: [`product-${id}`], lastModified: new Date(updatedAt) },
        };
      } catch (error) {
        return { error: error as Error };
      }
    },
  };
}

Three rules keep loaders predictable:

  1. Return { error } instead of throwing, so pages can decide how to handle failure.
  2. Return undefined from loadEntry() when nothing matches; Astro turns that into a not-found error for the caller.
  3. Keep id out of data. Each entry is { id, data }, with optional rendered: { html } for HTML content and an optional cacheHint.

Query live data in a page

Import the query functions from astro:content. They return results with an error property rather than throwing:

---
// src/pages/shop/index.astro
import { getLiveCollection } from 'astro:content';
import Layout from '../../layouts/Layout.astro';

export const prerender = false;

const category = Astro.url.searchParams.get('category') ?? undefined;
const { entries: products, error } = await getLiveCollection('products', { category });
---
<Layout title="Shop">
  <h1>Shop</h1>
  {error ? (
    <p>Products are unavailable right now. Please try again shortly.</p>
  ) : (
    <ul>
      {products.map((p) => (
        <li>
          <a href={`/shop/${p.id}/`}>{p.data.name}</a>, ${p.data.price}
          {!p.data.inStock && <span> (out of stock)</span>}
        </li>
      ))}
    </ul>
  )}
</Layout>

For a single entry, pass a filter object (or just the ID string, when the filter is { id }):

---
// src/pages/shop/[id].astro
import { getLiveEntry } from 'astro:content';
import Layout from '../../layouts/Layout.astro';

export const prerender = false;

const { entry: product, error } = await getLiveEntry('products', { id: Astro.params.id! });
if (error || !product) {
  return Astro.redirect('/404/');
}
---
<Layout title={product.data.name}>
  <h1>{product.data.name}</h1>
  <p>${product.data.price}</p>
</Layout>

The second argument to getLiveCollection() is passed to your loader as filter, and its type comes from the loader’s generic parameters, so editors autocomplete valid filter keys.

Error handling

The error returned by the query functions is one of:

  • The error your loader returned (for example a network failure).
  • LiveEntryNotFoundError when loadEntry() returned undefined.
  • LiveCollectionValidationError when data failed the schema.
  • LiveCollectionCacheHintError when a cache hint is malformed.

All extend LiveCollectionError, so you can branch on the class if you need different responses, for example a 404 for not found and a 503 for a failed upstream. Logging the error message on the server and showing a friendly message to visitors is usually enough.

Caching live data

Calling an API on every request is fine for low traffic, but you rarely need data that is fresh to the millisecond. Astro 7 has built-in route caching for on-demand responses: configure a provider, then pass the entry (with its cache hint) to Astro.cache.set():

// astro.config.mjs
import { defineConfig, memoryCache } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  adapter: node({ mode: 'standalone' }),
  cache: { provider: memoryCache() },
  routeRules: {
    '/shop/[...path]': { maxAge: 60, swr: 300 },
  },
});
---
// src/pages/shop/[id].astro (excerpt)
const { entry: product } = await getLiveEntry('products', { id: Astro.params.id! });
if (product) Astro.cache.set(product); // applies its tags and lastModified
---

Tags from cache hints let you purge related pages later with Astro.cache.invalidate() in an endpoint called by your CMS webhook. Some adapters configure a platform cache provider for you; check your adapter’s documentation. In development, the cache object exists but does not cache.

You can also set plain HTTP headers yourself, for example Cache-Control: s-maxage=60, stale-while-revalidate=300, and let your CDN handle it.

Rendering HTML from a live loader

If your API returns HTML (a CMS rich text field rendered to HTML), include it as rendered: { html } in the entry, then render it with render():

---
// src/pages/news/[id].astro
import { getLiveEntry, render } from 'astro:content';
export const prerender = false;

const { entry } = await getLiveEntry('news', { id: Astro.params.id! });
const { Content } = entry ? await render(entry) : { Content: null };
---
{Content && <article><Content /></article>}

Only render HTML from sources you trust, because it is inserted without escaping.

Live collections vs alternatives

  • Build-time collection with rebuild webhooks. Fastest pages, simplest hosting. Best for content that changes a few times a day.
  • Live collection. Typed, validated, queried like other content. Best for frequently changing data that pages render directly.
  • Server islands. Keep the page static and defer only the live part with server:defer. Best when most of the page is static and one block (price, stock, recommendations) must be fresh.
  • Endpoint plus client fetch. Best for interactive widgets that refresh in the browser.

A product page can combine them: static description from a build-time collection, live price in a server island backed by a live collection. The live content collections reference documents the loader API in full.

Most marketing and editorial sites never need live data. Every Komal Astro theme ships with build-time collections and static output, which you can extend with a live collection when a page needs it.

FAQ

What is the difference between content collections and live collections in Astro?

Content collections load at build time and are stored in Astro’s data store, so pages can be static. Live collections call their loader on every request, so data is always current, and they require on-demand rendering.

Where do I define live collections?

In src/live.config.ts, using defineLiveCollection() from astro:content. Build-time collections stay in src/content.config.ts.

Can I use live collections on a static site?

Not on prerendered pages. Live queries run at request time, so the page needs export const prerender = false and an adapter. Other pages on the site can stay static.

Do live collections support schemas?

Yes. Pass a Zod schema (import z from astro/zod) to defineLiveCollection(), and Astro validates each entry, returning a LiveCollectionValidationError if data does not match.

Are live collections slower than regular collections?

Each request waits for the loader, so response time depends on your API. Use route caching, cache hints or a CDN to avoid calling the API on every view.