Server Endpoints

Astro isn't just for static sites. Build full-stack applications with API routes, form handling, and server-side logic.

i

Full-Stack Astro

Astro can handle server-side logic through API routes (endpoints). These run on the server and can connect to databases, call external APIs, process forms, and more. Perfect for adding dynamic functionality to your static site.

Newsletter Signup

POST /api/subscribe

API Explorer

Interactive

Creating API Routes

GET Endpoint typescript
// src/pages/api/stats.ts
import type { APIRoute } from 'astro';

export const GET: APIRoute = async ({ url }) => {
  const section = url.searchParams.get('section');

  const stats = await fetchStats(section);

  return new Response(
    JSON.stringify({ success: true, data: stats }),
    {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
      },
    }
  );
};
POST Endpoint typescript
// src/pages/api/subscribe.ts
import type { APIRoute } from 'astro';

export const POST: APIRoute = async ({ request }) => {
  const { email, name } = await request.json();

  // Validate input
  if (!email || !isValidEmail(email)) {
    return new Response(
      JSON.stringify({ error: 'Invalid email' }),
      { status: 400 }
    );
  }

  // Save to database
  await db.subscribers.create({ email, name });

  return new Response(
    JSON.stringify({ success: true }),
    { status: 200 }
  );
};

Available Endpoints

Method Endpoint Description
GET /api/stats Returns site statistics and metrics
GET /api/stats?section=visitors Returns only visitor statistics
POST /api/subscribe Subscribe to newsletter (email, name)
GET /api/subscribe Returns endpoint documentation

Why Server Endpoints?

Secure by Default

Server code never reaches the client. API keys, database connections, and business logic stay on the server.

Same Codebase

No need for a separate backend. Your API lives alongside your pages in the same Astro project.

Edge Ready

Deploy to Cloudflare Workers, Vercel Edge, or Deno Deploy for globally distributed, low-latency APIs.