Skip to main content
InterviewHubPRO
Section Overview
Q18

Question 18 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

36%
Astro Islands & SSR (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

How do Astro Middleware functions work (`src/middleware.ts`)?

senior LevelCode ExampleSystem DesignAstro

In Simple Words: Runs on every incoming HTTP request before page rendering:

typescript
import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware(async (context, next) => {
  const token = context.cookies.get('session')?.value;

  if (!token && context.url.pathname.startsWith('/admin')) {
    return context.redirect('/login');
  }

  // Pass user to Astro components via locals
  context.locals.user = await getUserFromToken(token);
  return next();
});