Learn Astro Β· 11/15

Middleware: Intercepting Requests

6 min read

Welcome back, Astro-naut! πŸš€ Today we are entering the control room of your application.

Imagine your website is a very exclusive club. Right now, anyone can walk in, order a drink (request a page), and leave. But what if you want to check IDs at the door? What if you want to stamp their hand before they enter? What if you want to secretly stick a "Kick Me" sign on their back as they leave? (Okay, maybe not that last one).

In the world of web frameworks, this "Door Bouncer" is called Middleware.


1. What is Middleware in Astro?

The Definition

Middleware is code that runs before your specific page or API route is rendered. It sits between the user's request and your application's logic.

In Astro, middleware allows you to intercept requests and responses, inject data, or redirect users dynamically without having to copy-paste logic into every single .astro file.

The Problem it Solves

Without middleware, if you wanted to check if a user is logged in on 50 different dashboard pages, you would have to write the authentication check 50 times. That is a violation of the DRY (Don't Repeat Yourself) principle and a recipe for bugs. If you forget page #49, you have a security hole.

How to Create Middleware

Astro looks for a very specific file. You cannot name it stuff-that-runs.ts. It must be exact.

  1. Create a file named middleware.ts (or .js) inside your src/ folder.
  2. Export a function named onRequest.

File Structure:

text
src/
β”œβ”€β”€ components/
β”œβ”€β”€ pages/
β”œβ”€β”€ middleware.ts  <-- The Magic File πŸ§™β€β™‚οΈ
└── env.d.ts

The Basic Syntax

The onRequest function receives two arguments:

  1. context: Information about the current request (cookies, url, locals).
  2. next: A function that, when called, allows the request to proceed to the actual page.
typescript
// src/middleware.ts
import { defineMiddleware } from "astro:middleware";

// 'defineMiddleware' isn't strictly required but gives great Type safety!
export const onRequest = defineMiddleware((context, next) => {
  console.log("Request received for:", context.url.pathname);
  
  // Call next() to let the user see the page
  return next();
});

What happens here?
Every time you refresh your localhost, your terminal will log the path. You have successfully intercepted the request!


2. Modifying Responses and Appending Headers

Sometimes you don't just want to look at the request; you want to tamper with the result.

The Problem

You want to add security headers (like HSTS) to every page, or perhaps a custom header like X-Powered-By: Astro-Rocket-Fuel for branding. Doing this manually in astro.config.mjs is possible for some things, but doing it dynamically based on the user is impossible without middleware.

The Solution

The next() function returns a Response object (standard Web API Response). You can capture that response, modify it, and then return it to the browser.

Hands-on Example πŸ› οΈ

Let's add a custom header and measure how long the server took to build the page.

typescript
// src/middleware.ts
import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware(async (context, next) => {
  const start = Date.now();

  // 1. Let the page render (await is crucial!)
  const response = await next();

  // 2. Calculate time taken
  const end = Date.now();
  const duration = end - start;

  // 3. Mutate the response headers
  response.headers.set("X-Server-Timing", `${duration}ms`);
  response.headers.set("X-Built-With", "Love-and-Caffeine");

  // 4. Return the modified response
  return response;
});

Industry Tip: This is frequently used for Server-Timing headers to debug performance issues or to set Cache-Control headers dynamically.


3. Passing Context Data Across Routes with Astro.locals πŸ•΅οΈ

This is arguably the most important feature of Middleware.

The Problem

Let's say your middleware decodes a session cookie and finds out the user is "User ID: 42".
The middleware knows who the user is. But now the request continues to src/pages/profile.astro.
How does profile.astro know who the user is? You don't want to decode the cookie again inside the page (waste of resources).

The Solution: locals

locals is an object attached to the context. It lives only for the lifespan of that one request. It allows you to pass data from Middleware -> Page.

Step 1: Define the Type (TypeScript)

If you are using TypeScript (and you should be), you need to tell Astro what data you plan to store in locals.

Open (or create) src/env.d.ts:

typescript
// src/env.d.ts
/// <reference path="../.astro/types.d.ts" />

declare namespace App {
  interface Locals {
    user: {
      name: string;
      id: number;
      role: 'admin' | 'guest';
    } | null;
    isLoggedIn: boolean;
  }
}

Step 2: Set the data in Middleware

typescript
// src/middleware.ts
import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware((context, next) => {
  // Imagine we checked a cookie here
  const fakeUserFromCookie = {
    name: "Elon Musk",
    id: 1,
    role: "admin"
  };

  // Store it in locals
  context.locals.user = fakeUserFromCookie;
  context.locals.isLoggedIn = true;

  return next();
});

Step 3: Access it in your Component

Now, inside any .astro page, Astro.locals is available and fully typed!

astro
---
// src/pages/index.astro
const { user, isLoggedIn } = Astro.locals;
---

<h1>Welcome!</h1>
{isLoggedIn ? (
  <p>Hello, {user?.name}. We have been expecting you.</p>
) : (
  <button>Login</button>
)}

4. Protecting Routes (Authentication Checks)

Now we combine everything to build a real security gate.

The Problem

You have a /dashboard and /settings page. If a user tries to access them without being logged in, they should be kicked back to the /login page immediately.

The Solution

We check the context.url in middleware. If it matches a protected path and locals.user is missing, we return a Redirect response instead of calling next().

Important Concept: If you return a Response directly (like a redirect), the next() function is never called, and the destination page (dashboard.astro) never even starts rendering. It saves server resources! πŸ›‘οΈ

Hands-on Example πŸ›‘οΈ

typescript
// src/middleware.ts
import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware((context, next) => {
  
  // 1. Simulate checking auth (in real life, check session/cookies)
  const isAuthenticated = false; // Change to true to test access
  
  // 2. Define protected routes
  const protectedRoutes = ["/dashboard", "/settings", "/profile"];
  
  // 3. Check if current URL is protected
  const isProtectedRoute = protectedRoutes.some(route => 
    context.url.pathname.startsWith(route)
  );

  // 4. The Bouncer Logic
  if (isProtectedRoute && !isAuthenticated) {
    // STOP! Do not pass Go. Do not call next().
    // Redirect them to login.
    return context.redirect("/login");
  }

  // 5. If safe, proceed
  return next();
});

Fun Fact: This is exactly how "Guards" work in frameworks like NestJS or Angular, but simplified for the Astro era.


5. Advanced: Chaining Middleware (The Conveyor Belt)

In a large app, you might have separate files for logging, auth, and error handling. You don't want one giant middleware.ts file with 500 lines of code.

Astro provides a helper called sequence.

typescript
// src/middleware.ts
import { sequence } from "astro:middleware";

async function validation(context, next) {
    console.log("Step 1: Validating...");
    return next();
}

async function auth(context, next) {
    console.log("Step 2: Checking Auth...");
    return next();
}

// They run in order: validation -> auth -> page
export const onRequest = sequence(validation, auth);

This creates a conveyor belt. Step 1 must finish before Step 2 starts.


πŸ“š Resources & Further Reading

Summary:

  1. Middleware intercepts requests.
  2. Use src/middleware.ts and export onRequest.
  3. Use context.locals to pass data to pages (Type it in env.d.ts!).
  4. Return context.redirect() to protect routes.
  5. Always call next() unless you want to stop the request.

Now go guard those routes! πŸ’‚β€β™‚οΈ

Challenge

You are given an array of product objects. Write a function calculateTotalDiscountedElectronics that processes this array to calculate the total cost for a specific subset of products.

Your function must perform the following operations in sequence:

  1. Filter the array to include only products that are in stock (where the inStock property is true).
  2. From the result of the first step, filter again to include only products belonging to the 'Electronics' category.
  3. Take the list of in-stock electronics and apply a 10% discount to the price of each item.
  4. Finally, calculate the sum of these new discounted prices and return the total.

You must use a combination of the .filter(), .map(), and .reduce() array methods to achieve this. The function should return a single number representing the final total.

Expected result

Your code should correctly implement the calculateTotalDiscountedElectronics function. When called with the provided products array, it should chain or sequentially use the filter, map, and reduce methods to process the data as described in the instructions. The function must ultimately return the number 2070.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.