Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท SSR, Adapters and Endpoints

API Endpoints and Server Routes in Astro

Build Astro endpoints that return JSON, handle POST requests, read params and headers, generate static files at build time and return correct status codes.

Not every URL returns an HTML page. Astro lets you add endpoints: files in src/pages/ that export functions named after HTTP methods and return a Response. Use them for JSON APIs, RSS feeds, robots.txt, image generation, webhooks, or anything the browser or another service asks for.

Your first endpoint

Create a .js or .ts file in src/pages/. The file name becomes the URL, and the extension before the last dot becomes part of it: src/pages/api/hello.json.ts is served at /api/hello.json.

TypeScript
// src/pages/api/hello.json.ts
import type { APIRoute } from 'astro';

export const GET: APIRoute = ({ url }) => {
  const name = url.searchParams.get('name') ?? 'world';
  return Response.json({ message: `Hello, ${name}!` });
};

Response.json(data) sets the status and the JSON content-type header. The handler receives a context object (APIContext) with request, url, params, cookies, locals, redirect, clientAddress, site and more.

Methods

Export one function per method: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. A fallback ALL handles any method you did not define.

TypeScript
// src/pages/api/notes.ts
import type { APIRoute } from 'astro';

export const prerender = false;

const notes = new Map<number, string>();
let nextId = 1;

export const GET: APIRoute = () => Response.json([...notes].map(([id, text]) => ({ id, text })));

export const POST: APIRoute = async ({ request }) => {
  if (!request.headers.get('content-type')?.includes('application/json')) {
    return Response.json({ error: 'Expected JSON' }, { status: 415 });
  }
  const body = await request.json().catch(() => null);
  if (!body || typeof body.text !== 'string' || body.text.trim() === '') {
    return Response.json({ error: 'text is required' }, { status: 400 });
  }
  const id = nextId++;
  notes.set(id, body.text.trim());
  return Response.json({ id, text: body.text.trim() }, { status: 201 });
};

export const ALL: APIRoute = () =>
  new Response(null, { status: 405, headers: { allow: 'GET, POST' } });

This code needs prerender = false (or output: 'server') because it reacts to requests. The in-memory Map is only for illustration: on serverless platforms the process may restart between requests, so a real app stores data in a database.

Status codes to know

Code Use
200 OK / 201 Created Success / resource created
204 No Content Success with no body
400 Bad Request Invalid input
401 / 403 Not logged in / not allowed
404 Not Found Missing resource
405 Method Not Allowed Wrong HTTP method
415 Unsupported Media Type Wrong content-type
429 Too Many Requests Rate limited
500 Server error

Dynamic parameters

Bracketed names work as in pages:

TypeScript
// src/pages/api/notes/[id].ts
export const prerender = false;

export const GET: APIRoute = ({ params }) => {
  const id = Number(params.id);
  if (!Number.isInteger(id)) return Response.json({ error: 'Invalid id' }, { status: 400 });
  return Response.json({ id });
};

Rest parameters ([...path].ts) catch many segments.

Static endpoints: files at build time

Without prerender = false, an endpoint runs once at build and its GET result becomes a file. That is perfect for feeds and data files on a fully static site:

TypeScript
// src/pages/posts.json.ts
import { getCollection } from 'astro:content';

export async function GET() {
  const posts = await getCollection('blog');
  const data = posts.map((p) => ({ slug: p.id, title: p.data.title }));
  return new Response(JSON.stringify(data), {
    headers: { 'content-type': 'application/json' },
  });
}

Output: dist/posts.json. With dynamic names add getStaticPaths, exactly as for pages:

TypeScript
// src/pages/og/[slug].png.ts
export function getStaticPaths() {
  return [{ params: { slug: 'hello' } }, { params: { slug: 'islands' } }];
}

Other useful responses

TypeScript
// robots.txt
export const GET: APIRoute = ({ site }) =>
  new Response(`User-agent: *\nAllow: /\nSitemap: ${new URL('sitemap-index.xml', site)}\n`);

// redirect
export const GET: APIRoute = ({ redirect }) => redirect('/new-place', 301);

// streaming a download
export const GET: APIRoute = () =>
  new Response('id,name\n1,Ada\n', {
    headers: {
      'content-type': 'text/csv',
      'content-disposition': 'attachment; filename="people.csv"',
    },
  });

Security checklist

  1. Validate input. Never trust request.json(); check types and sizes (Astro Actions, covered later, does this for you with Zod).
  2. Authenticate and authorise each handler; middleware helps.
  3. CSRF. Astro checks the Origin header on cross-site form POSTs by default (security.checkOrigin). Keep it enabled.
  4. No secrets in responses and no raw error messages to clients.
  5. CORS. Endpoints send no CORS headers by default; add them deliberately and narrowly.
  6. Rate-limit public write endpoints at the platform or in middleware.

Calling endpoints from a page

From an island, use fetch('/api/notes', ...). From a server-rendered .astro page, you can call your own logic directly instead of making an HTTP round-trip: put it in a shared module and import it in both the page and the endpoint.

Try it: a mini router

A stand-in for how a request finds its handler: file-style routes with params, method checks and JSON responses. It uses the standard Request and Response, which your browser and Astro share.

JS Endpoint router

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: a static endpoint's output

A static endpoint is a function run once per path at build time. This stand-in produces an RSS file the way a rss.xml.ts endpoint would, with proper XML escaping.

JS Build rss.xml at build time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where is the URL /api/hello.json defined?

    Endpoints live in src/pages/, and the file name (including the inner extension) forms the URL.
  2. 2. What does a static endpoint (no prerender = false) do?

    On a prerendered route the handler's GET result becomes a file in dist, such as posts.json.
  3. 3. Which status code fits a POST with a malformed JSON body?

    400 Bad Request tells the client its input was wrong. 500 would claim the server failed.
  4. 4. What should you export to answer every method you did not define?

    ALL handles methods without their own export; a common use is returning 405 with an Allow header.

Summary

  • Endpoints are files in src/pages/ exporting GET, POST, etc. that return Response.
  • Dynamic ones need prerender = false; static ones become files at build time.
  • Use correct status codes, validate input, authenticate and keep CORS narrow.
  • getStaticPaths generates many static endpoint files.

Next: Middleware, Cookies and Sessions