DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Efficiently Migrating From Jest to Vitest in a Next.js Project
  • Serverless Sign-In Solution Based on Next.js on CloudFare
  • Next.js Theming: CSS Variables for Adaptive Data Visualization

Trending

  • How to Build Local LLM RAG Apps With Ollama, DeepSeek-R1, and SingleStore
  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • Fixing Common Oracle Database Problems
  • Integrating Security as Code: A Necessity for DevSecOps
  1. DZone
  2. Coding
  3. JavaScript
  4. Introduction to Next.js Middleware: How It Works With Examples

Introduction to Next.js Middleware: How It Works With Examples

Next.js middleware lets you handle requests before they hit your routes. Use it for tasks like redirects and authentication, with examples to guide you.

By 
Sheraz Manzoor user avatar
Sheraz Manzoor
·
Oct. 16, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
5.8K Views

Join the DZone community and get the full member experience.

Join For Free

Let's talk about routing in Next.js. Today, we will talk about the one of most powerful things: middleware. Middleware in Next.js offers a powerful and flexible way both to intercept requests from the server and control request flow (redirects, URL rewriting) and globally enhance features like authentication, headers, and cookie persistence.

Creating Middleware

Let's create a Middleware Next.js application. First of all, we'll create a new file for middleware like middleware.js or middleware.ts, in the src folder. Middleware in Next.js then needs to allow you fine control over where it will be active (ie custom matcher configuration, or using isXXX functions)

Redirecting

Using redirection as an example, let's imagine a scenario where navigating to /profile should redirect the user to the homepage. With the custom matcher configuration approach, we can achieve this by importing the necessary types, defining a middleware function, and specifying the matcher configuration:

JavaScript
 
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {  return NextResponse.redirect(request.url.replace('/profile', '/'));
}

export const config = {  matcher: '/profile',
};


In this example, the middleware function checks if the request URL path is /profile and redirects the user to the homepage.

For the conditional statement approach, we can modify the code as follows:

JavaScript
 
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {  if (request.nextUrl.pathname === '/profile') {    return NextResponse.redirect('/hello');  }  return NextResponse.next();
}


In this case, the middleware checks the request URL path and redirects the user to the /hello route if the path is /profile.

Middleware in Next.js goes beyond just handling redirections. It also allows for URL rewrites, which can be useful for legacy URL support or SEO optimization. By changing redirect to rewrite in the previous examples, the URL in the browser will stay the same (/profile), but the response content will change to the content from the /hello route.

Using Cookies

Lastly, let's explore the use of cookies and headers in middleware. We can modify our middleware to handle user preferences for themes and add a custom header for all responses:

JavaScript
 
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {  const response = NextResponse.next();
  // Handle user theme preference  const themePreference = request.cookies.get('theme');  if (!themePreference) {    response.cookies.set('theme', 'dark');  }
  // Add a custom header  response.headers.set('Custom-Header', 'Custom Value');
  return response;
}


In this example, we first check if the user has a theme preference stored in a cookie. If not, we set the theme to 'dark' by adding a cookie. Then, we add a custom header to the response, which can be useful for passing additional information or for debugging purposes.

As you can see, middleware in Next.js is a powerful tool that allows you to effectively control and intercept the request-response cycle, enabling redirects, URL rewrites, and the manipulation of headers and cookies. By mastering middleware, you can enhance the routing experience in your Next.js applications and create more robust and customizable user experiences.

"Middleware in Next.js is a powerful feature that offers a robust way to intercept and control the flow of requests and responses within your applications." — Next.js Documentation

Conclusion

In summary, we've learned how to define middleware in Next.js, explore the two main approaches (custom matcher configuration and conditional statements), and apply middleware to handle redirections, URL rewrites, and the management of cookies and headers. This knowledge will help you take your Next.js applications to the next level by leveraging the flexibility and control that middleware provides.

Next.js Middleware

Published at DZone with permission of Sheraz Manzoor. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Efficiently Migrating From Jest to Vitest in a Next.js Project
  • Serverless Sign-In Solution Based on Next.js on CloudFare
  • Next.js Theming: CSS Variables for Adaptive Data Visualization

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!