Middleware is a powerful pattern that allows you to intercept and process HTTP requests before they reach your application routes. Think of middleware as a security checkpoint or filter that examines every incoming request and decides what to do with it.
In web applications, middleware functions sit between the client's request and your server's response. They can modify requests, add headers, perform authentication checks, log information, or even redirect users to different pages. This makes middleware perfect for cross-cutting concerns like authentication, logging, and security.
The key concept is that middleware has access to both the request object (containing URL, headers, cookies, etc.) and the ability to generate responses. It can either:
Authentication middleware specifically checks whether a user has the proper credentials (usually stored in cookies or headers) to access protected resources. If they don't, it redirects them to a login page instead of showing the protected content.
Cookies are commonly used for authentication because they're automatically sent with every request to the same domain. The middleware can parse these cookies to find authentication tokens and make access decisions. This pattern ensures that authentication logic is centralized and consistently applied across your entire application.
1// Basic middleware pattern for logging requests
2function loggingMiddleware(request: Request): Response {
3 const url = new URL(request.url);
4 console.log(`${request.method} ${url.pathname}`);
5
6 // Check if this is an API route
7 if (url.pathname.startsWith('/api/')) {
8 // Add custom header and continue
9 return new Response(null, {
10 status: 200,
11 headers: { 'X-API-Version': '1.0' }
12 });
13 }
14
15 // For non-API routes, just continue
16 return new Response(null, { status: 200 });
17}