Next.js Middleware Explained: Simple Guide with Examples

Sheraz ManzoorSheraz Manzoor
3 min read

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

Creating Middleware

Let's create 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 the 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:

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:

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:

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.

0
Subscribe to my newsletter

Read articles from Sheraz Manzoor directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sheraz Manzoor
Sheraz Manzoor

I am an experienced Frontend Developer currently working at Infinity Devs as a MERN Stack Developer. With a deep passion for creating intuitive and dynamic web applications, I specialize in technologies like React, Next.js, Typescript, zod, SaaS and Tailwind CSS. I pride myself on delivering clean, efficient, and responsive designs that not only meet but exceed client expectations. In my career, I have worked on everything from tiny websites for small businesses to complete custom web applications. With such a strong understanding of client needs, I utilize my own technical capabilities to create new solutions. By making my user experiences better or performance faster Key Skills: -Frontend Technologies: React, Next.js, HTML, CSS, JavaScript, Tailwind CSS -Version Control: Git, GitHub -Responsive Design: Mobile-first development, cross-browser compatibility -Collaboration: Excellent communication skills, experience in agile environments Professional Approach: -Shared Ownership: I believe in collaborative effort and shared responsibility to ensure the success of every project. -Rapid Execution: Efficiently managing time and resources to deliver quality work promptly -Show and Tell: Regular updates and transparency with clients to ensure alignment and satisfaction -Bias for Action: Prioritizing proactive measures to tackle challenges head-on -Systematic Approach: Methodical planning and execution to maintain high standards -Design Thinking: Emphasizing empathy and creativity to solve complex problems and deliver user-centric solutions Interests: When I’m not coding, you can find me exploring the latest in tech, reading about advancements in AI, or enjoying a good book. I also have a keen interest in photography and love capturing moments in nature.