Next.js: Creating a Middleware for Advanced Request Handling.

Search for a command to run...

No comments yet. Be the first to comment.
The Problem Wasn’t Triage Most AI workflows in software engineering still keep the human directly in the middle of triage. The AI might help write code. It might explain a stack trace. It might summar

There’s been a steady undercurrent of people switching tools lately. Copilot to Claude. Claude to something else. Codex quietly entering more workflows. A lot of confidence in different directions, of

It’s been said to me that at times my responses can come across as a “no” first-unintentionally, of course, but real all the same. Not long ago, someone on my team shared an idea they were exploring. I began with a caution, meaning to help them avoid...

The opening sentence of any message often carries more weight than everything that follows. I’ve learned this the hard way. Recently, a report shared something he wanted to pursue. I was supportive — I really was — but my first response came as a cau...

One of the things I’ve always been comfortable with is admitting when I don’t know something. To me, it’s one of the real distinctions between the more and less experienced engineers — and honestly, people in general. When you’re earlier in your care...

Middleware is a feature that lets you run logic before a request is completed. You can use it to:
Redirect users.
Protect routes (authentication).
Modify responses.
Handle custom headers or logging.
Imagine you have a dashboard that should only be accessible to authenticated users. Middleware makes it easy to check the authentication token and redirect unauthorized users.
Middleware files must be named middleware.ts and placed in the root of your app.
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
// Check for a token in cookies (example: `authToken`)
const token = request.cookies.get('authToken')?.value;
// If no token, redirect to login
if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Allow request to continue
return NextResponse.next();
}
// Specify routes where middleware applies
export const config = {
matcher: ['/dashboard/:path*'], // Apply middleware to all /dashboard routes
};
Now, if a user accesses /dashboard or any subpage like /dashboard/settings, they will be redirected to /login unless they have a valid authToken cookie.
You can also modify the request or response directly in middleware. For example, logging user details or setting custom headers:
export function middleware(request: NextRequest) {
// Log the user's IP
console.log('User IP:', request.ip);
// Add a custom header to the response
const response = NextResponse.next();
response.headers.set('X-Custom-Header', 'Middleware Works!');
return response;
}
Run your app locally (npm run dev or yarn dev) and try accessing the protected routes. If you’re using cookies, you can simulate adding an authToken in your browser’s dev tools.
Authentication and Authorization: Redirect unauthorized users or check user roles.
Localization: Dynamically redirect users based on their location or language preference.
Rate Limiting: Throttle requests to APIs or routes.
Logging and Monitoring: Log request details (e.g., IP address or user agent).
Dynamic Content Delivery: Serve different versions of content based on request headers or cookies.
Performance: Middleware runs before rendering, reducing client-side overhead.
Scalability: Centralizes logic for route handling and request validation.
Security: Helps enforce route protection and authentication without cluttering your page code.
Mastering middleware opens up a whole new layer of possibilities in Next.js for building secure, dynamic, and efficient apps!