Server-Side Astro
The idea in one sentence
Section titled “The idea in one sentence”Astro is static by default, but you opt into the server whenever a page needs request-time work — the logged-in user, a form submission, live data, an auth check. The server is a tool you reach for deliberately, not the default substrate.
Everything in this module is about that opt-in: rendering per request, handling requests directly, calling server logic type-safely, and running code before every request.
What this module covers
Section titled “What this module covers”| Lesson | What you’ll learn |
|---|---|
| SSR & adapters | On-demand rendering, adapters, and reading the request |
| Endpoints & API routes | APIRoute handlers that return a Response |
| Actions | Type-safe server functions with defineAction and validation |
| Middleware & sessions | onRequest, context.locals, and Astro.session |
Four ways to run server code
Section titled “Four ways to run server code”flowchart TB req["Incoming request"] --> mw["Middleware onRequest (runs first, every request)"] mw --> page["On-demand page (prerender false)"] mw --> api["API endpoint (GET/POST handler)"] mw --> act["Action handler (defineAction)"] page --> resp["Response"] api --> resp act --> resp
- On-demand pages render HTML per request, so they can read cookies, the user, and query params.
- API endpoints are non-HTML routes — return JSON, a file, a webhook reply — as a raw
Response. - Actions are type-safe server functions you call from the client with validated input, ideal for mutations and forms.
- Middleware runs before every request, the place for auth, logging, and shared per-request data.