Astro endpoints are .js or .ts files in src/pages/ that export HTTP method functions such as GET or POST and return a standard Response. On a static site, an endpoint runs once at build time and writes a file (/feed.json, /robots.txt). With export const prerender = false and an adapter, the same file becomes a server API route that runs on every request.
This guide shows both modes, dynamic endpoints with getStaticPaths(), the context object, form handling, and the mistakes that cause empty responses or 404s.
Key Takeaways
- The file name sets the output:
src/pages/data.json.tsbuilds/data.json.- Static endpoints only handle
GETat build time and cannot read request headers.- Add
export const prerender = falseplus an adapter to acceptPOST,PUTandDELETE.- Every handler must return a
Responseobject, or Astro throwsEndpointDidNotReturnAResponse.HEADrequests fall back to yourGEThandler; unhandled methods get a 404.
What an Astro endpoint is
An endpoint is a route that returns data instead of HTML. Astro uses the same file-based routing as pages: put the file in src/pages/, and its path becomes the URL. The difference is the file type and what it exports.
// src/pages/hello.json.ts
import type { APIRoute } from 'astro';
export const GET: APIRoute = () => {
return new Response(JSON.stringify({ message: 'Hello from Astro' }), {
headers: { 'Content-Type': 'application/json' },
});
};
The .json before .ts is part of the output name. Astro strips only the final .ts, so the build writes dist/hello.json. Name a file robots.txt.ts and you get /robots.txt; name it sitemap.xml.ts and you get /sitemap.xml.
If you are still learning how files map to URLs, the Astro routing guide covers pages, and pages and routing in a theme shows where endpoints sit in a real project.
Static endpoints: files generated at build time
On the default static output, endpoints are prerendered. Astro calls your GET once during astro build and saves the response body to disk. There is no server at runtime, so the result can be served by any static host.
This is the right tool for any machine-readable file built from your content:
// src/pages/posts.json.ts
import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';
// `site` comes from astro.config.mjs and must be set for absolute URLs.
export const GET: APIRoute = async ({ site }) => {
const posts = await getCollection('blog', ({ data }) => !data.draft);
const body = posts
.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf())
.map((post) => ({
title: post.data.title,
url: new URL(`/blog/${post.id}/`, site).href,
date: post.data.pubDate.toISOString(),
}));
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
});
};
Common static endpoints in real projects:
- A search index (
/search.json) that a small client script fetches. robots.txtthat switches rules based on an environment variable.- A JSON feed,
llms.txt, or a custom XML file for a partner. - Generated Open Graph images returned as PNG bytes.
Two limits apply. First, only GET runs, because there is no request to answer at build time; if you export POST from a prerendered endpoint, Astro logs a warning that those requests are not available in static endpoints. Second, request.headers and cookies are empty, since the build is not responding to a real visitor.
Dynamic static endpoints with getStaticPaths
Endpoints can use dynamic segments just like pages. Export getStaticPaths() to tell Astro which files to generate:
// src/pages/api/posts/[id].json.ts
import type { APIRoute, GetStaticPaths } from 'astro';
import { getCollection, getEntry } from 'astro:content';
export const getStaticPaths = (async () => {
const posts = await getCollection('blog');
return posts.map((post) => ({ params: { id: post.id } }));
}) satisfies GetStaticPaths;
export const GET: APIRoute = async ({ params }) => {
const post = await getEntry('blog', params.id!);
if (!post) return new Response(null, { status: 404 });
return new Response(JSON.stringify({ title: post.data.title, tags: post.data.tags }), {
headers: { 'Content-Type': 'application/json' },
});
};
This builds one JSON file per post. The params work exactly as they do for pages, which the getStaticPaths guide explains in detail, including props and rest parameters.
Server endpoints: API routes on demand
To handle form submissions, webhooks or anything that depends on the incoming request, the endpoint must run on a server. Install an adapter for your host (Node.js, Netlify, Vercel or Cloudflare) and opt the route out of prerendering:
// src/pages/api/subscribe.ts
import type { APIRoute } from 'astro';
export const prerender = false;
export const POST: APIRoute = async ({ request }) => {
const contentType = request.headers.get('content-type') ?? '';
if (!contentType.includes('application/json')) {
return new Response(JSON.stringify({ error: 'Expected JSON' }), { status: 415 });
}
const { email } = await request.json();
if (typeof email !== 'string' || !email.includes('@')) {
return new Response(JSON.stringify({ error: 'Invalid email' }), { status: 400 });
}
// Save the address with your email provider's API here.
return new Response(JSON.stringify({ ok: true }), {
status: 201,
headers: { 'Content-Type': 'application/json' },
});
};
Without an adapter, a prerender = false route fails the build with the NoAdapterInstalled error; the no adapter installed fix walks through it. If most of your site is server-rendered, set output: 'server' in the config instead and mark the few static pages with export const prerender = true.
Export one function per method you support: GET, POST, PUT, PATCH, DELETE, or ALL as a catch-all. Astro picks the handler that matches request.method, falls back to ALL, and serves HEAD requests from GET with the body removed. Method names must be uppercase. A lowercase all export is ignored, and Astroβs warning suggests the fix.
The context object
Every handler receives an APIContext. The fields you will use most:
| Field | Use |
|---|---|
request |
The standard Request: method, headers, json(), formData() |
params |
Values of dynamic segments such as [id] |
url |
Parsed URL of the request, including searchParams |
cookies |
Read and set cookies with get(), set(), delete() |
redirect(path, status) |
Return a redirect Response |
locals |
Data set by middleware for this request |
site |
Your site config value as a URL |
clientAddress |
Visitor IP, on adapters that support it |
props |
Props passed from getStaticPaths() |
Query strings are a frequent need in search or filter endpoints:
// src/pages/api/search.ts
import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';
export const prerender = false;
export const GET: APIRoute = async ({ url }) => {
const q = (url.searchParams.get('q') ?? '').trim().toLowerCase();
if (q.length < 2) return Response.json([]);
const posts = await getCollection('blog');
const hits = posts
.filter((post) => post.data.title.toLowerCase().includes(q))
.slice(0, 20)
.map((post) => ({ title: post.data.title, url: `/blog/${post.id}/` }));
return Response.json(hits);
};
Response.json() is the standard shorthand that sets the JSON content type for you. It is part of the Fetch standard, so it works in every runtime Astro supports.
Handling HTML form posts
A plain HTML form can post straight to an endpoint. Read it with formData() and redirect back, so the browser does not resubmit on refresh:
// src/pages/api/contact.ts
import type { APIRoute } from 'astro';
export const prerender = false;
export const POST: APIRoute = async ({ request, redirect }) => {
const data = await request.formData();
const name = String(data.get('name') ?? '').trim();
const message = String(data.get('message') ?? '').trim();
if (!name || !message) {
return redirect('/contact/?error=missing', 303);
}
// Send the message with your email service here.
return redirect('/contact/thanks/', 303);
};
---
// src/pages/contact.astro
---
<form method="POST" action="/api/contact">
<label>Name <input name="name" required /></label>
<label>Message <textarea name="message" required></textarea></label>
<button type="submit">Send</button>
</form>
For typed validation and error handling without writing the endpoint plumbing, look at Astro Actions, which generate type-safe server functions on top of the same request model. If your site is fully static and you only need a contact form, a third-party form service may be simpler; static contact forms in Astro compares the options.
Returning non-JSON responses
A Response can carry anything. Set the right Content-Type and, for server routes, sensible caching headers:
// src/pages/robots.txt.ts
import type { APIRoute } from 'astro';
export const GET: APIRoute = ({ site }) => {
const isProduction = import.meta.env.PROD;
const body = isProduction
? `User-agent: *\nAllow: /\nSitemap: ${new URL('/sitemap-index.xml', site).href}\n`
: 'User-agent: *\nDisallow: /\n';
return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } });
};
Binary data works the same way: return an ArrayBuffer, Uint8Array or stream as the body and set Content-Type: image/png. Static endpoints write those bytes into dist/ as a normal file.
Common endpoint mistakes
Most endpoint bugs come down to a handful of causes:
- Returning a plain object.
return { ok: true }throwsEndpointDidNotReturnAResponse. Wrap it inResponse.json(). The endpoint no response fix shows the exact error. - Expecting POST on a static site. Prerendered endpoints only answer
GETat build time. Addprerender = falseand an adapter. - Forgetting the extension in the file name.
posts.tsbuilds/posts, served without a JSON content type by many static hosts. Useposts.json.ts. - Reading headers at build time.
request.headersis empty when the endpoint is prerendered. - Unsupported methods. A
PUTto a route that only exportsPOSTgets a 404, not a 405. Add anALLhandler if you want to return405 Method Not Allowedyourself.
The official endpoints guide and the APIContext reference list every field and option.
Many sites only need static endpoints: a search index, a feed, a robots file. Every Komal theme builds to static files, so endpoints like these work on any host without a server. You can browse Astro themes if you want a starting point that already has its pages and feeds in place.
FAQ
What is the difference between a static and a server endpoint in Astro?
A static endpoint runs once during the build and writes a file to dist/. A server endpoint has export const prerender = false, needs an adapter, and runs on every request, so it can read headers, cookies and request bodies.
Can Astro endpoints handle POST requests on a static site?
No. Prerendered endpoints only run GET at build time. To accept POST, mark the route with export const prerender = false and install an adapter, or send the form to an external service.
Where do I put API routes in an Astro project?
Anywhere inside src/pages/. Most projects use src/pages/api/ so URLs read /api/subscribe, but the folder name has no special meaning to Astro.
How do I return JSON from an Astro endpoint?
Return Response.json(data), or new Response(JSON.stringify(data)) with a Content-Type: application/json header. Returning a plain object throws an error.
Do Astro endpoints support TypeScript?
Yes. Name the file .ts and type the handler with APIRoute from astro, which types params, request, cookies and the other context fields.