Skip to main content
Middleware in Astro allows you to intercept requests and responses, modify data, add authentication, log requests, and perform other server-side operations before rendering pages.

Basic Middleware

Create middleware by defining a middleware.ts file in your src/ directory:
src/middleware.ts
Middleware runs on every request in SSR mode, and during build time for pre-rendered pages.

The Context Object

Middleware receives a context object with request information and helpful utilities:
src/middleware.ts

Available Properties

Request
The incoming HTTP request
URL
Parsed URL object
Record<string, string>
Route parameters from dynamic routes
AstroCookies
Cookie utilities for reading/writing cookies
App.Locals
Shared data object passed to pages
(path: string, status?: number) => Response
Helper to create redirect responses
(path: string) => Promise<Response>
Internally rewrite to a different URL
string
Client’s IP address

Authentication Example

Implement authentication in middleware:
src/middleware.ts
Access the user in your pages:
src/pages/dashboard.astro
Use context.locals to share data between middleware and your pages. Type it by creating src/env.d.ts.

Sequencing Middleware

Chain multiple middleware functions using sequence:
src/middleware.ts
Each middleware in the sequence:
src/middleware/logger.ts
src/middleware/cors.ts
Middleware executes in the order specified:
  1. logger runs first
  2. cors runs second
  3. auth runs last
  4. Page handler executes
  5. Response bubbles back through middleware
Any middleware can return early, skipping subsequent middleware:

Modifying Responses

Modify responses before they’re sent:
src/middleware.ts

Redirects and Rewrites

Redirects

Return redirect responses to send users to different URLs:
src/middleware.ts

Rewrites

Internally rewrite requests to different routes without changing the URL:
src/middleware.ts
Rewrites keep the original URL in the browser while serving different content. Use redirects to change the browser URL.
Work with cookies in middleware:
src/middleware.ts
string
Cookie path. Default: ’/’
string
Cookie domain
Date
Expiration date
number
Max age in seconds
boolean
HTTP-only flag (not accessible via JavaScript)
boolean
Secure flag (HTTPS only)
'strict' | 'lax' | 'none'
SameSite attribute

Type Safety

Type your locals object for better TypeScript support:
src/env.d.ts
Now context.locals and Astro.locals are fully typed:
src/middleware.ts

API Routes

Middleware also runs for API routes:
src/pages/api/data.ts

Common Patterns

src/middleware/rate-limit.ts

Conditional Middleware

Run middleware conditionally based on the route:
src/middleware.ts

Actions

Handle form submissions

SSR

Server-side rendering

API Routes

Build API endpoints

Authentication

Authentication patterns