Exploring Next.js Middleware
Hey there, today I wanted to discuss Next.js middleware, a feature that every serious app needs to use. What I like about it is that it's very easy to set up, but yet it does so much for you. So let me show you what I mean by that.
Table of Contents
What is Middleware in Next.js?
Imagine that your web app is a nightclub, and middleware is the bouncer at the door. This bouncer decides who gets in based on their IDs. In Next.js, middleware acts as this gatekeeper for your app’s requests, letting you run code before the request completes. It’s perfect for tasks like authentication, logging, modifying requests, and more—all before the user even hits your page.
Why I Love Middleware
You might be wondering why you should bother with middleware. Let me tell you, it’s been a game-changer for me. Here’s why:
Getting Started with Middleware in Next.js
Let’s get our hands dirty with some code.
Setting Up Middleware
Create a middleware.js file in your rootdirectory. Here’s an example that uses an config object to handle different middleware scenarios:
// middleware.js
import { NextResponse } from 'next/server';
export const config = {
matcher: '/dashboard/:path*',
};
export function middleware(req) {
const token = req.cookies.token;
if (!token) {
return NextResponse.redirect('/login', req.url);
}
return NextResponse.next();
}
In this example, the config object uses the matcher property to specify that this middleware should apply to any route under /dashboard. If there’s no token cookie, the middleware redirects the user to the login page. This way, we can protect our dashboard routes efficiently.
领英推荐
More Cool Stuff You Can Do
Here are a few more ways I’ve found middleware to be incredibly handy:
Logging Requests
Logging is crucial for keeping tabs on what’s happening in your app. Here’s how you can log requests:
export const config = {
matcher: '/api/:path*',
};
export function middleware(req) {
console.log(`Request to ${req.nextUrl.pathname} at ${new Date().toISOString()}`);
return NextResponse.next();
}
Every request to any route under /api logs the pathname and timestamp. This simple addition has helped me a lot in debugging and understanding user behavior.
A/B Testing
A/B testing can be a powerful tool to improve your user experience. Here’s how you can set it up with middleware:
export const config = {
matcher: '/',
};
export function middleware(req) {
const url = req.nextUrl.clone();
const variant = Math.random() < 0.5 ? 'A' : 'B';
if (url.pathname === '/') {
url.pathname = `/home-${variant}`;
return NextResponse.rewrite(url);
}
return NextResponse.next();
}
With this setup, users visiting the homepage are randomly redirected to either /home-A or /home-B, letting you gather data on which version works better.
Personal Tips for Using Middleware
From my experience, keeping middleware simple is key. Middleware runs on every request, so you want to ensure it’s efficient and doesn’t slow things down. Here are a few tips:
My Takeaway
Playing around with middleware in Next.js has been a revelation. It’s given me a cleaner, more efficient way to handle common tasks like authentication and logging. I love how it centralizes control logic, making my codebase cleaner and more maintainable.
I encourage you to try it out in your next project. Middleware can help you handle requests more gracefully and make your web apps more robust. Plus, it’s a lot of fun to see just how much you can do before your users even reach a page!
Happy coding, and let me know in the comments how you’re using middleware in your projects. I’d love to hear your stories and tips! ??
Frontend Developer @ Listed Hosting | React, Mobile Web
5 个月Wow. I learnt a lot from this video
AI/LLM Disruptive Leader | GenAI Tech Lab
6 个月Thanks for sharing! See also other cool stuff you can do with NextJS, at https://mltblog.com/4bWk1A2
Building HoverConsole.com | Entrepreneur | Visionary
6 个月Awesome
hello there
6 个月Love seeing how Next.js keeps evolving!
Full-stack Engineer as a REACT JS Developer
6 个月Thank you! This post came right in time for my app