Live content collections — следующая эволюция контента в Astro, приносящая возможности данных в реальном времени в знакомый API content collections, который вы уже знаете и любите.
Content collections в Astro прошли несколько этапов эволюции. Они начались как невероятно простой и мощный способ управлять структурированным контентом из файлов на диске. Изначально поддерживая Markdown, MDX и JSON, они позволяют строить блоги, документационные сайты и многое другое с отличным developer experience и типобезопасными данными.
С Astro 5.0 content collections расширились в полноценный Content Layer с подключаемыми loaders для всех типов источников данных, включая API, CMS и многое другое.
В Astro 5.10 content collections делают следующий шаг с экспериментальной поддержкой live content collections. С ними можно получать контент во время runtime вместо build time, открывая совершенно новые возможности для динамического, персонализированного и real-time контента.
Строите ли вы e-commerce с часто меняющимися остатками, новостной сайт со срочными обновлениями или дашборд с live-метриками — новые live content collections Astro дают нужную гибкость, сохраняя типобезопасность и developer experience, которые делают Astro особенным.
Основы Live Content Collections
Прежде чем погружаться в live content collections, стоит понять основу, на которой они построены: loaders. Astro content collections используют loaders для управления структурированными данными и контентом в проектах. Каждая content collection полагается на свой loader для определения заполнения записей. Во время astro build эти loaders получают данные и заполняют локальный data store. Страницы затем запрашивают этот неизменяемый снимок через getCollection() и getEntry().
Live content collections идут дальше: вместо получения данных на этапе сборки они получают их во время запроса, давая доступ к максимально свежим данным. Иногда нужна скорость и надёжность статического контента, а иногда — гибкость и динамика live-данных. Как вы выбираете между статическими и on-demand страницами в Astro, теперь можно выбирать между build-time и live content collections.
Какой бы выбор ни сделали, вы получаете тот же знакомый API из существующих content collections. Если вы знаете getCollection() и getEntry(), вы уже знаете большую часть того, что нужно для getLiveCollection() и getLiveEntry().
Архитектура live collections
В отличие от build-time content collections, заполняющих статический data store во время сборки, live content collections работают принципиально иначе под капотом:
Когда запрашивается страница с live content collections:
- Страница вызывает
getLiveCollection()илиgetLiveEntry()для получения данных. - Данные получаются из внешнего источника (API, база данных и т.д.).
- Результаты обрабатываются и валидируются по вашей схеме.
- Данные возвращаются в компонент страницы.
Эта архитектура означает, что вы всегда работаете со свежими данными, но каждый запрос включает сетевые вызовы к источникам данных. Этот компромисс идеален, когда свежесть данных важнее абсолютной производительности. Проблемы производительности можно смягчить кэшированием страниц, а live collections помогают cache hints для оптимизации. По мере развития экспериментальной функции Astro в итоге возьмёт больше на себя. Пока можно использовать Cache-Control и другие заголовки для контроля времени кэширования в браузере и на CDN.
Настройка Live Content Collections
Для начала работы с live content collections нужно включить экспериментальный флаг и создать конфигурацию live collection:
export default defineConfig({ experimental: { liveContentCollections: true, }, // Live collections require an adapter for on-demand rendering adapter: node({ mode: 'standalone', }),});Затем создайте файл src/live.config.ts для определения live collections, указав type: 'live' и loader коллекции.
В этом примере я использую два live loader пакета, которые создал, но вам, вероятно, нужно будет создать свои loaders для своих live-источников данных по нашей документации. Мы ждём больше community loaders — делитесь тем, что построите! (Мне потребовалось несколько часов, чтобы добавить поддержку live loader в существующие feed loader и Bluesky loader пакеты для build-time collections, так что начать, надеюсь, несложно.)
import { defineLiveCollection } from 'astro:content';import { liveFeedLoader } from '@ascorbic/feed-loader';import { liveBlueskyLoader } from '@ascorbic/bluesky-loader';
export const astroNews = defineLiveCollection({ type: 'live', loader: liveFeedLoader({ url: 'https://astro.build/rss.xml', }),});
export const socialPosts = defineLiveCollection({ type: 'live', loader: liveBlueskyLoader({ identifier: 'astro.build', limit: 10, }),});Получение live-данных на страницах
После определения live collections использование на страницах очень похоже на существующие build-time content collections, с несколькими ключевыми отличиями. В частности, стоит добавить обработку ошибок, поскольку данные загружаются live из внешнего источника:
---export const prerender = false;
import { getLiveCollection } from 'astro:content';
// Fetch the latest Astro blog postsconst { entries: blogPosts, error } = await getLiveCollection('astroNews');
if (error) { console.error('Failed to load news:', error);}---
<h1>Latest Astro News</h1>{ error ? ( <p>Unable to load news at this time. Please try again later.</p> ) : ( <div class="news-grid"> {blogPosts.map((post) => ( <article class="news-card"> <h2> <a href={post.data.url}>{post.data.title}</a> </h2> {post.data.description && ( <p class="summary">{post.data.description}</p> )} </article> ))} </div> )}Также можно использовать getLiveEntry() для получения одной записи по ID или с параметрами фильтра:
---export const prerender = false;
import { getLiveEntry, render } from 'astro:content';const postId = Astro.params.id;const { entry: post, error } = await getLiveEntry('socialPosts', postId);if (error) { console.error('Failed to load post:', error); return Astro.rewrite('/404');}
const { Content } = await render(post);---
<div class="post"> <Content /> <div class="engagement-stats"> <span>❤️ {post.data.likeCount}</span> <span>🔄 {post.data.repostCount}</span> <span>💬 {post.data.replyCount}</span> {post.data.quoteCount > 0 && <span>📝 {post.data.quoteCount}</span>} </div></div>Создание live content loader
Создание кастомных live loaders позволяет подключаться к любому API или источнику данных с полным контролем над получением и обработкой. API спроектирован простым, гибким и типобезопасным — вы можете строить loaders под свои нужды, сохраняя простоту и типобезопасность Astro. Мы будем рады, если люди попробуют экспериментальный API и дадут обратную связь, чтобы улучшить его до стабилизации.
Создание кастомного API Loader
Пример live loader для e-commerce API:
import type { LiveLoader } from 'astro:content';
interface Product { id: string; name: string; price: number; category: string; inStock: boolean; description?: string;}
interface ProductFilter { category?: string; inStock?: boolean;}
export function createStoreLoader( baseUrl: string,): LiveLoader<Product, ProductFilter> { return { loadCollection: async (filter) => { try { const url = new URL(`${baseUrl}/products`);
if (filter?.category) { url.searchParams.set('category', filter.category); } if (filter?.inStock !== undefined) { url.searchParams.set('inStock', filter.inStock.toString()); }
const response = await fetch(url); if (!response.ok) { return { error: new Error( `Failed to fetch products: ${response.statusText}`, ), }; }
const data = await response.json(); return { entries: data.map((product: Product) => ({ id: product.id, data: product, })), }; } catch (error) { return { error: error instanceof Error ? error : new Error('Unknown error'), }; } },
loadEntry: async (id) => { try { const response = await fetch(`${baseUrl}/products/${id}`); if (response.status === 404) { return { entry: null }; } if (!response.ok) { return { error: new Error(`Failed to fetch product: ${response.statusText}`), }; }
const product = await response.json(); return { entry: { id: product.id, data: product, }, }; } catch (error) { return { error: error instanceof Error ? error : new Error('Unknown error'), }; } }, };}Затем используйте в конфигурации live collections:
import { defineLiveCollection, z } from 'astro:content';import { createStoreLoader } from './loaders/store-loader';
export const products = defineLiveCollection({ type: 'live', loader: createStoreLoader('https://store.example.com'), schema: z.object({ id: z.string(), name: z.string(), price: z.number(), category: z.string(), inStock: z.boolean(), description: z.string().optional(), }),});Loader с отрендеренным контентом
Live content loaders могут поддерживать отрендеренный контент, упрощая отображение HTML, полученного из API. Пример blog post loader, получающего посты из CMS и рендерящего контент как HTML:
import type { LiveLoader } from 'astro:content';
interface BlogPost { title: string; author: string; publishDate: Date; content: string; excerpt: string; tags: string[];}
interface BlogFilter { status?: 'published' | 'draft'; author?: string;}
export function createBlogLoader( baseUrl: string,): LiveLoader<BlogPost, BlogFilter> { return { loadCollection: async (filter) => { try { const url = new URL(`${baseUrl}/posts`);
if (filter?.status) { url.searchParams.set('status', filter.status); } if (filter?.author) { url.searchParams.set('author', filter.author); }
const response = await fetch(url); if (!response.ok) { return { error: new Error(`Failed to fetch posts: ${response.statusText}`), }; }
const posts = await response.json(); return { entries: posts.map((post: any) => ({ id: post.slug, data: { title: post.title, author: post.author, publishDate: new Date(post.publishDate), content: post.content, excerpt: post.excerpt, tags: post.tags || [], }, rendered: post.html ? { html: post.html } : undefined, })), }; } catch (error) { return { error: error instanceof Error ? error : new Error('Unknown error'), }; } },
loadEntry: async (slug) => { try { const response = await fetch(`${baseUrl}/posts/${slug}`); if (response.status === 404) { return { entry: null }; } if (!response.ok) { return { error: new Error(`Failed to fetch post: ${response.statusText}`), }; }
const post = await response.json(); return { entry: { id: post.slug, data: { title: post.title, author: post.author, publishDate: new Date(post.publishDate), content: post.content, excerpt: post.excerpt, tags: post.tags || [], }, rendered: post.html ? { html: post.html } : undefined, }, }; } catch (error) { return { error: error instanceof Error ? error : new Error('Unknown error'), }; } }, };}Затем используйте в конфигурации live collections:
import { defineLiveCollection, z } from 'astro:content';import { createBlogLoader } from './loaders/blog-loader';
export const blogPosts = defineLiveCollection({ type: 'live', loader: createBlogLoader('https://cms.example.com'), schema: z.object({ title: z.string(), author: z.string(), publishDate: z.date(), content: z.string(), excerpt: z.string(), tags: z.array(z.string()), }),});Live collections vs build-time collections
Понимание, когда использовать live collections вместо традиционных build-time collections, критично для производительных приложений:
Используйте live collections, когда:
- Данные часто меняются: уровни запасов, пользовательский контент, live-метрики
- Нужна персонализация: персональные рекомендации, данные дашборда
- Критична точность в реальном времени: новостные ленты, контент соцсетей, live-счёт
- Нужна динамическая фильтрация: результаты поиска, отфильтрованные каталоги продуктов
Используйте build-time collections, когда:
- Контент относительно статичен: посты блога, документация, маркетинговые страницы
- Производительность на первом месте: высоконагруженные сайты, где важна каждая миллисекунда
- Нужны трансформации изображений или MDX-рендеринг: Live collections не поддерживают трансформации изображений или MDX-рендеринг
Гибридные подходы
Можно комбинировать оба подхода в одном проекте и даже на одной странице. Например, build-time collections для статического контента вроде постов блога, а live collections для динамических функций вроде комментариев или профилей пользователей.
---export const prerender = false;
import { getEntry, getLiveCollection } from 'astro:content';
// Контент поста блога получается на этапе сборки и кэшируется в data store. Сайт пересобирается при добавлении новых постовconst post = await getEntry('blog', Astro.params.slug);
// Live-комментарии получаются во время запроса, поэтому всегда показывают последние комментарииconst { entries: comments } = await getLiveCollection('comments', { postId: Astro.params.slug,});---
<!-- Статический контент поста блога --><article> <h1>{post.data.title}</h1> <Content /></article>
<!-- Секция live-комментариев --><section class="comments"> <h2>Comments ({comments.length})</h2> { comments.map((comment) => ( <div class="comment"> <strong>{comment.data.author}</strong> <p>{comment.data.content}</p> </div> )) }</section>Такие гибридные паттерны хорошо сочетаются с server islands, позволяя создавать по-настоящему гибридные страницы, где основной контент статичен, а отдельные компоненты получают live-данные. Лучшее из обоих миров: быстрая доставка статического контента с динамическими real-time секциями.
---// Эту страницу можно prerender, потому что основной контент статиченimport { getEntry, getCollection } from 'astro:content';import Comments from '../components/Comments.astro';
export const getStaticPaths = async () => { const posts = await getCollection('blog'); return posts.map((post) => ({ params: { slug: post.id }, }));};
const post = await getEntry('blog', Astro.params.slug);---
<!-- Статический контент поста блога --><article> <h1>{post.data.title}</h1> <div class="content"> <Content /> </div></article>
<!-- Динамические комментарии через server island --><Comments server:defer postId={Astro.params.slug} />---export const prerender = false;
import { getLiveCollection } from 'astro:content';
interface Props { postId: string;}
const { postId } = Astro.props;
// Этот компонент работает как server island, получая live-данныеconst { entries: comments, error } = await getLiveCollection('comments', { postId, status: 'approved',});
// Кэшировать в CDN на 10 минутAstro.response.headers.set('Cache-Control', 'public, s-maxage=600');---
<section> <h2>Comments</h2> {error ? ( <p>Unable to load comments at this time.</p> ) : comments.length === 0 ? ( <p>No comments yet. Be the first to comment!</p> ) : ( <div class="comments-list"> {comments.map((comment) => ( <div class="comment"> <div class="comment-header"> <strong>{comment.data.author}</strong> <time>{comment.data.createdAt.toLocaleDateString()}</time> </div> <p>{comment.data.content}</p> </div> ))} </div> )}</section>Этот подход даёт несколько преимуществ: быстрая начальная загрузка страницы со статическим контентом при возможности для отдельных компонентов получать live-данные по необходимости. Также можно эффективно кэшировать live-данные, улучшая производительность и снижая нагрузку на API.
Обработка ошибок и устойчивость
Live content collections предоставляют явную обработку ошибок, делающую приложение устойчивее:
---export const prerender = false;
import { getLiveCollection } from 'astro:content';
// Получить несколько live collections с индивидуальной обработкой ошибокconst [metricsResult, alertsResult, reportsResult] = await Promise.all([ getLiveCollection('metrics'), getLiveCollection('alerts', { severity: 'high' }), getLiveCollection('reports', { recent: true }),]);
// Обрабатывать ошибки gracefullyconst metrics = metricsResult.error ? [] : metricsResult.entries;const alerts = alertsResult.error ? [] : alertsResult.entries;const reports = reportsResult.error ? [] : reportsResult.entries;
const hasErrors = metricsResult.error || alertsResult.error || reportsResult.error;---
{ hasErrors && ( <div class="error-banner"> Some dashboard data may be outdated. Please refresh to try again. </div> )}
<div class="dashboard"> <section class="metrics"> <h2>Metrics</h2> { metrics.length === 0 ? ( <p>No metrics available</p> ) : ( <div class="metrics-grid"> {metrics.map((metric) => ( <div class="metric-card"> <h3>{metric.data.name}</h3> <p class="value">{metric.data.value}</p> </div> ))} </div> ) } </section>
<section class="alerts"> <h2>High Priority Alerts</h2> { alerts.length === 0 ? ( <p>No alerts - all systems operational</p> ) : ( <ul class="alerts-list"> {alerts.map((alert) => ( <li class="alert"> <strong>{alert.data.title}</strong> <p>{alert.data.description}</p> </li> ))} </ul> ) } </section></div>Соображения производительности и лучшие практики
При использовании live content collections важно учитывать влияние на производительность, особенно с медленными или сложными API. Несколько лучших практик:
Кэширование с cache hints
Live content collections поддерживают cache hints для метаданных кэширования ответов. Это помогает оптимизировать производительность через правильные cache headers и стратегии инвалидации кэша. В будущих версиях Astro cache hints будут использоваться для автоматического кэширования страниц, но пока их можно использовать для установки подходящих HTTP-заголовков на страницах.
import type { LiveLoader } from 'astro:content';
interface Product { id: string; name: string; price: number; lastModified: string; category: string;}
export function createStoreLoader(baseUrl: string): LiveLoader<Product> { return { loadCollection: async (filter) => { try { const response = await fetch(`${baseUrl}/products`); if (!response.ok) { return { error: new Error( `Failed to fetch products: ${response.statusText}`, ), }; }
const products = await response.json();
return { entries: products.map((product: Product) => ({ id: product.id, data: product, cacheHint: { tags: [`product-${product.id}`], lastModified: new Date(product.lastModified), }, })), cacheHint: { tags: ['products'], }, }; } catch (error) { return { error: error instanceof Error ? error : new Error('Unknown error'), }; } },
loadEntry: async (id) => { try { const response = await fetch(`${baseUrl}/products/${id}`); if (response.status === 404) { return { entry: null }; } if (!response.ok) { return { error: new Error(`Failed to fetch product: ${response.statusText}`), }; }
const product = await response.json();
return { entry: { id: product.id, data: product, }, cacheHint: { tags: [`product-${id}`], lastModified: new Date(product.lastModified), }, }; } catch (error) { return { error: error instanceof Error ? error : new Error('Unknown error'), }; } }, };}Затем используйте cache hints на страницах для установки подходящих HTTP-заголовков:
---export const prerender = false;
import { getLiveEntry } from 'astro:content';
const { entry: product, error, cacheHint,} = await getLiveEntry('products', Astro.params.id);
if (error || !product) { return Astro.redirect('/products');}
// Установить cache headers на основе cache hintif (cacheHint?.lastModified) { Astro.response.headers.set( 'Last-Modified', cacheHint.lastModified.toUTCString(), );}if (cacheHint?.tags) { Astro.response.headers.set('Cache-Tag', cacheHint.tags.join(','));}
// Установить свои cache control headersAstro.response.headers.set('Cache-Control', 'public, max-age=600'); // 10 minutes---
<h1>{product.data.name}</h1><p>Price: ${product.data.price}</p>Обратите внимание: cache hints предоставляют метаданные о контенте, но вам всё равно нужно устанавливать свои cache headers для контроля фактического кэширования. Платформы вроде Netlify позволяют инвалидировать кэши по этим тегам, чтобы live-контент оставался свежим без лишних API-вызовов.
Реальные use case
Каталог продуктов e-commerce
---export const prerender = false;
import { getLiveCollection, getLiveEntry } from 'astro:content';
const slug = Astro.params.slug;
const { entry: product, error } = await getLiveEntry('products', slug);
if (error || !product) { return Astro.redirect('/products');}
// Также получить связанные продуктыconst { entries: related } = await getLiveCollection('products', { category: product.data.category, exclude: product.id, limit: 4,});
// Рендер деталей продукта и связанных элементов...---Агрегация новостей и соцсетей
Пример с community loaders для live-дашборда новостей и соцсетей:
---export const prerender = false;
import { getLiveCollection } from 'astro:content';
// Получить live RSS feed через community loaderconst { entries: astroNews, error: newsError } = await getLiveCollection('astroNews');
// Получить live Bluesky посты через community loaderconst { entries: socialPosts, error: socialError } = await getLiveCollection('socialPosts');
const hasErrors = newsError || socialError;---
<div class="dashboard"> { hasErrors && ( <div class="error-banner"> Some content may be unavailable. Please refresh to try again. </div> ) }
<section class="news-section"> <h2>Latest Tech News</h2> { newsError ? ( <p>Unable to load news at this time.</p> ) : ( <div class="news-grid"> {astroNews.map((article) => ( <article class="news-card"> <h3> <a href={article.data.link} target="_blank"> {article.data.title} </a> </h3> <p class="meta"> {article.data.pubDate?.toLocaleDateString()} |{' '} {article.data.creator} </p> {article.data.summary && ( <p class="summary">{article.data.summary}</p> )} </article> ))} </div> ) } </section>
<section class="social-section"> <h2>Latest from Bluesky</h2> { socialError ? ( <p>Unable to load social posts at this time.</p> ) : ( <div class="posts-feed"> {socialPosts.map((post) => ( <div class="post-card"> <div class="post-header"> <strong>{post.data.author.displayName}</strong> <span class="handle">@{post.data.author.handle}</span> <time>{post.data.createdAt.toLocaleString()}</time> </div> <div class="post-content"> {post.rendered && <Fragment set:html={post.rendered.html} />} </div> </div> ))} </div> ) } </section></div>Использование кастомных loaders на страницах
После создания кастомных loaders их можно использовать на страницах:
---export const prerender = false;
import { getLiveEntry } from 'astro:content';
// Получить один продукт с обработкой ошибокconst { entry: product, error } = await getLiveEntry( 'products', Astro.params.id,);
if (error) { console.error('Failed to load product:', error); return Astro.redirect('/products');}
if (!product) { return Astro.redirect('/products');}---
<h1>{product.data.name}</h1><p class="price"> { new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', }).format(product.data.price) }</p><p class="stock-status"> {product.data.inStock ? 'In Stock' : 'Out of Stock'}</p>{ product.data.description && ( <div class="description"> <p>{product.data.description}</p> </div> )}Будущее Live Content Collections
Live content collections сейчас экспериментальны, но представляют важный шаг в эволюции Astro, открывая больше use case для сайтов с динамическим real-time контентом на Astro при сохранении любимого developer experience.
Следующие шаги
Live content collections экспериментальны в Astro 5.10, и нам нужна ваша обратная связь. Чтобы участвовать:
- Читайте документацию, чтобы начать с live content collections в Astro-проектах.
- Читайте RFC и делитесь обратной связью.
- Посмотрите мои пакеты live RSS feed loader и Bluesky loader, чтобы понять, как они работают, и изучить паттерны.
- Создайте свой loader и поделитесь с сообществом! Расскажите, что построили — мы можем помочь с продвижением.
Live content collections открывают захватывающие возможности для динамических real-time веб-опытов при сохранении любимого developer experience. Строите ли e-commerce, новостную платформу или data dashboard — live collections дают гибкость и мощь для по-настоящему динамических веб-приложений.
