Using Middleware in Next.js

Search for a command to run...

No comments yet. Be the first to comment.
Dynamic routing in Next.js allows you to create flexible routes that adapt to user input. This feature is particularly useful for building dynamic applications like blogs, e-commerce sites, and user-specific dashboards. Additionally, Next.js provides...
If you’re building modern web applications, chances are you’ve needed a simple backend for tasks like storing form submissions, feedback requests, or lightweight data logs. Instead of spinning up a server or managing databases, what if you could just...

Real-time applications, such as chat apps, require instant data exchange between clients and servers. In this guide, we'll walk through integrating Socket.io with Next.js (App Router) to build a real-time chat application. 🚀 Why Use Socket.io with ...

Managing global state in a Next.js application can be tricky, but Redux Toolkit (RTK) makes it easier by reducing boilerplate and improving performance. In this guide, we’ll walk through integrating Redux Toolkit with Next.js to efficiently manage ap...

Firebase is a powerful backend-as-a-service platform that offers authentication, real-time databases, and hosting. Integrating Firebase with a Next.js application allows you to build scalable and serverless web applications with ease. Why Use Fireba...

Optimization in Next.js App

Middleware in Next.js allows you to run code before a request is completed. It’s a powerful tool for tasks like authentication, logging, redirects, and more. With middleware, you can enhance your application’s behavior on both server-side and edge functions, improving performance and user experience.
Middleware is a function that executes during the request lifecycle. It allows you to modify the request or response before it reaches its destination.
Runs on Edge: Middleware executes on Vercel’s Edge Network for optimal performance.
Dynamic Control: Modify responses, redirect users, or authenticate requests dynamically.
File-Based: Like routes, middleware is file-based.
Middleware is defined in a middleware.ts file at the root of your src directory.
src/middleware.ts
Here’s an example of middleware that redirects users who are not logged in to a login page:
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const isAuthenticated = request.cookies.get('auth-token');
if (!isAuthenticated) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*'], // Apply middleware to specific routes
};
NextRequest: Represents the incoming request.
NextResponse: Used to send responses like redirects or modifications.
matcher: Specifies the routes where the middleware should apply.
One common use case for middleware is protecting routes that require authentication.
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('auth-token');
if (!token) {
return NextResponse.redirect(new URL('/signin', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/profile/:path*', '/settings/:path*'],
};
If the auth-token cookie is missing, the user is redirected to the /signin page.
Middleware is applied to routes like /profile and /settings.
You can use middleware to dynamically redirect users based on conditions, such as locale or device type.
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const country = request.geo?.country || 'US';
if (country === 'FR') {
return NextResponse.redirect(new URL('/fr', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/'],
};
request.geo: Provides geolocation information.
Users from France (FR) are redirected to a localized /fr page.
To debug your middleware, use console.log() statements. However, remember that middleware runs on the Edge, so logs appear in the Vercel dashboard or terminal during local development.
Middleware does not have access to environment variables.
Middleware cannot fetch data from APIs.
Middleware runs before static files are served, so it won’t apply to images or other public assets.
Middleware in Next.js provides a versatile way to handle authentication, redirection, and more. By running code before requests are completed, you can enhance your app’s functionality and user experience. Start experimenting with middleware today to see how it can streamline your Next.js applications!