The Astro container API renders an .astro component in isolation and returns its HTML as a string or a Response, without building a page or starting a server. You import experimental_AstroContainer from astro/container, create a container, and call renderToString(Component, { props, slots }). Its main use is unit testing components with Vitest, and it also lets you render Astro components inside endpoints or scripts, for example to generate HTML emails or snippets.
The API is still marked experimental (hence the experimental_ prefix), so its surface may change in a minor release. This guide covers setup, testing patterns, the render options and the limits worth knowing.
Key Takeaways
const container = await experimental_AstroContainer.create()thenawait container.renderToString(Card, { props }).- Use
getViteConfig()fromastro/configinvitest.config.tsso tests can import.astrofiles.- Options include
props,slots,params,locals,request,routeTypeandpartial.renderToResponse()returns a fullResponse, useful for testing status codes and headers of pages and endpoints.- Framework components (React, Vue, Svelte) need renderers added with
loadRenderers()oraddServerRenderer().
What the container API is for
Normally, Astro components only render as part of a page during astro dev or astro build. That makes them hard to test: you would have to build a page, then inspect the output. The container API removes that step. It sets up just enough of Astro’s renderer to turn one component into HTML, in memory, from any JavaScript runtime where Vite can load .astro files.
Three common uses:
- Unit tests. Assert that a component renders the right markup for given props and slots.
- Snapshot tests. Catch unintended markup changes in shared components such as headers, cards and SEO tags.
- Rendering outside pages. Produce HTML from an Astro component in an endpoint, for emails, embeds or HTML fragments.
Set up Vitest
Install Vitest:
npm install -D vitest
Create a Vitest config that uses Astro’s Vite setup, so .astro imports and Astro’s virtual modules resolve:
// vitest.config.ts
/// <reference types="vitest/config" />
import { getViteConfig } from 'astro/config';
export default getViteConfig({
test: {
environment: 'node',
},
});
Add a script to package.json:
{
"scripts": {
"test": "vitest"
}
}
Your first component test
Take a simple card component:
---
// src/components/Card.astro
interface Props {
title: string;
href: string;
tag?: string;
}
const { title, href, tag } = Astro.props;
---
<article class="card">
{tag && <span class="tag">{tag}</span>}
<h3><a href={href}>{title}</a></h3>
<slot />
</article>
Test it with the container:
// src/components/Card.test.ts
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import { expect, test } from 'vitest';
import Card from './Card.astro';
test('renders title, link and tag', async () => {
const container = await AstroContainer.create();
const html = await container.renderToString(Card, {
props: { title: 'Rebrand for a bank', href: '/work/bank/', tag: 'Branding' },
});
expect(html).toContain('<a href="/work/bank/">Rebrand for a bank</a>');
expect(html).toContain('<span class="tag">Branding</span>');
});
test('omits the tag when none is given', async () => {
const container = await AstroContainer.create();
const html = await container.renderToString(Card, {
props: { title: 'Untagged', href: '/x/' },
});
expect(html).not.toContain('class="tag"');
});
Run npm test. Each test creates a container, renders the component with props, and checks the HTML string. Creating the container once in a beforeAll() hook speeds up larger suites.
Note that Astro adds scoped style attributes (such as data-astro-cid-*) to elements when the component has a <style> block, so match on content or use a regular expression rather than comparing whole tags when styles are present.
Passing slots
Slots are passed as strings, keyed by slot name. default is the unnamed slot:
// src/components/Card.test.ts (another test)
test('renders default slot content', async () => {
const container = await AstroContainer.create();
const html = await container.renderToString(Card, {
props: { title: 'With body', href: '/y/' },
slots: { default: '<p>Short summary</p>' },
});
expect(html).toContain('<p>Short summary</p>');
});
For named slots, use their names: slots: { header: 'Top', footer: 'Bottom' }. Slot values are inserted as HTML, so you can pass markup.
Locals, params and requests
Components that read Astro.locals, Astro.params or Astro.request need those values supplied:
---
// src/components/Greeting.astro
const user = Astro.locals.user;
---
<p>{user ? `Welcome back, ${user.name}` : 'Welcome, guest'}</p>
// src/components/Greeting.test.ts
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import { expect, test } from 'vitest';
import Greeting from './Greeting.astro';
test('greets a signed-in user', async () => {
const container = await AstroContainer.create();
const html = await container.renderToString(Greeting, {
locals: { user: { name: 'Sam' } },
});
expect(html).toContain('Welcome back, Sam');
});
Other options:
params: route params for components that readAstro.params, such as{ slug: 'hello' }.request: a customRequest, for testing code that reads headers, cookies or the URL.partial: defaults totrue, rendering the component without a full HTML document. Set it tofalsewhen rendering a page component that should include<!DOCTYPE html>.routeType: set to'endpoint'to render an API route module instead of a component.
Testing responses with renderToResponse
renderToResponse() returns a Response object, which lets you check status codes and headers, not just HTML:
// src/pages/api/health.test.ts
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import { expect, test } from 'vitest';
import * as health from './health.ts';
test('health endpoint returns JSON', async () => {
const container = await AstroContainer.create();
const response = await container.renderToResponse(health, { routeType: 'endpoint' });
expect(response.status).toBe(200);
expect(response.headers.get('content-type')).toContain('application/json');
expect(await response.json()).toMatchObject({ ok: true });
});
This works for page components too. A page that calls Astro.redirect() returns a response with a 3xx status and a Location header you can assert on.
Snapshot testing shared components
Snapshots catch accidental markup changes in components used everywhere, like an SEO head or a footer:
// src/components/SEO.test.ts
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import { expect, test } from 'vitest';
import SEO from './SEO.astro';
test('SEO head matches snapshot', async () => {
const container = await AstroContainer.create({
astroConfig: { site: 'https://www.example.com' },
});
const html = await container.renderToString(SEO, {
props: { title: 'About', description: 'About the studio' },
request: new Request('https://www.example.com/about/'),
});
expect(html).toMatchSnapshot();
});
The first run writes a snapshot file; later runs fail if the output changes. Review the diff, then update with vitest -u if the change was intended. If a component reads Astro.site, pass it when creating the container: AstroContainer.create({ astroConfig: { site: 'https://www.example.com' } }). The Astro SEO checklist has an SEO component worth covering this way.
Rendering framework components
If an Astro component renders React, Vue, Svelte or Solid components, the container needs that framework’s renderer. In Vitest, load renderers through the astro:container virtual module:
// src/components/Pricing.test.ts
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import { loadRenderers } from 'astro:container';
import { getContainerRenderer } from '@astrojs/react/container-renderer';
import { expect, test } from 'vitest';
import Pricing from './Pricing.astro';
test('renders the React price toggle on the server', async () => {
const renderers = await loadRenderers([getContainerRenderer()]);
const container = await AstroContainer.create({ renderers });
const html = await container.renderToString(Pricing);
expect(html).toContain('Monthly');
});
Outside Vite (for example in a server endpoint at runtime), add the server renderer directly with container.addServerRenderer(), and, if components use client:* directives, container.addClientRenderer() so the island markup references the right client entrypoint. The exact import paths depend on the framework integration version, so check the container API reference for your integration.
Rendering Astro components in an endpoint
The container also works at runtime. This endpoint renders an Astro email template to HTML:
// src/pages/api/preview-email.ts
import type { APIRoute } from 'astro';
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
import WelcomeEmail from '../../emails/WelcomeEmail.astro';
export const prerender = false;
export const GET: APIRoute = async ({ url }) => {
const container = await AstroContainer.create();
const html = await container.renderToString(WelcomeEmail, {
props: { name: url.searchParams.get('name') ?? 'there' },
});
return new Response(html, { headers: { 'Content-Type': 'text/html; charset=utf-8' } });
};
That lets you write email templates as Astro components with props and slots, then pass the HTML to your email provider. Because it runs per request, it needs on-demand rendering and an adapter.
Limits to know
- Experimental. The
experimental_prefix means breaking changes can land in minor releases. Pin your Astro version in projects that rely on it, and read release notes when upgrading. - No client-side execution. The container renders server HTML. It does not run
<script>tags or hydrate islands. Test browser behavior with Playwright or a DOM testing library. - Content collections and assets. Components that call
getCollection()or process images rely on Astro’s Vite plugins, whichgetViteConfig()provides in Vitest. Outside Vitest, prefer passing data as props. - Scoped style attributes appear in output and change when styles change, which affects exact string assertions and snapshots.
If you maintain a component library or a theme, a small suite of container tests catches regressions before they ship. Every Komal theme is a standard Astro project, so the Vitest setup above drops in as is. For component patterns worth testing, see the Astro components guide, and for how projects are laid out, the project structure docs.
FAQ
What is the Astro container API?
It is an API that renders a single .astro component outside of a page build and returns HTML or a Response. You create a container with experimental_AstroContainer.create() from astro/container and call renderToString() or renderToResponse() with props and slots.
How do I test Astro components with Vitest?
Use getViteConfig() from astro/config in vitest.config.ts, then in a test import your component and the container, render it with renderToString(Component, { props }), and assert on the returned HTML string with expect().
Is the Astro container API stable?
No. It is exported as experimental_AstroContainer, which means its API can change between minor versions. It is widely used for testing, but pin your Astro version and check release notes when upgrading.
Can the container API render React or Vue components?
Yes, if you provide renderers. In Vitest, load them with loadRenderers() from astro:container and pass them to create({ renderers }). At runtime, add them with addServerRenderer(), and add a client renderer for components that use client:* directives.
Does the container API run client-side scripts?
No. It only renders server-side HTML. Scripts are not executed and islands are not hydrated. Use a browser testing tool such as Playwright to test client-side behavior.