llms.txt Astro Guide: Generate Endpoints Automatically
In Astro, you can generate /llms.txt automatically at build time from your Content Collections so new docs, blog posts and API pages appear without manual edits. Below is the exact TypeScript endpoint pattern, plus static vs SSR caching options.
Create a Build-Time llms.txt Route in Astro
Place a file at src/pages/llms.txt.ts. Exporting prerender = true instructs Astro to emit a static dist/llms.txt file during astro build, even if your project uses a hybrid or server adapter like Cloudflare, Vercel or Node.
import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';
export const prerender = true;
export const GET: APIRoute = async ({ site }) => {
const origin = (site?.toString() || 'https://example.com').replace(/\/$/, '');
const docs = await getCollection('docs');
const lines = [
'# My Astro Site',
'',
'> Developer documentation and guides built with Astro.',
'',
'## Documentation',
...docs.map((entry) => `- [${entry.data.title}](${origin}/docs/${entry.id}): ${entry.data.description}`),
'',
];
return new Response(lines.join('\n'), {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
};import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';
export const prerender = true;
export const GET: APIRoute = async ({ site }) => {
const origin = (site?.toString() || 'https://example.com').replace(/\/$/, '');
const docs = await getCollection('docs');
const blocks = docs.map((entry) => [
`## ${entry.data.title}`,
`Source: ${origin}/docs/${entry.id}`,
'',
entry.body || entry.data.description,
].join('\n'));
const output = ['# My Astro Site — Full Context', '', ...blocks, ''].join('\n\n');
return new Response(output, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
};Verify Your Astro llms.txt Output
- Set
siteinastro.config.mjs— ensures every URL in your generated Markdown links is absolute (https://...) rather than relative. - Return
text/plain; charset=utf-8— prevents browsers and AI fetchers from mangling UTF-8 characters or downloading the file as binary. - Validate before deploying — open
http://localhost:4321/llms.txt, copy the output and paste it into the llms.txt Studio validator to verify zero spec errors.
Astro llms.txt Questions
Should I Use public/llms.txt or src/pages/llms.txt.ts in Astro?
Use public/llms.txt if your site has fewer than 10 static pages that rarely change. Use src/pages/llms.txt.ts whenever your site relies on Content Collections so newly published guides appear automatically on every build.
Does Astro Escape Markdown Inside APIRoute?
No. Returning a plain Response with Content-Type: text/plain; charset=utf-8 outputs the exact raw Markdown string you construct.