codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

57 / 73 topics
56Middleware Functions57Creating Middleware58Using Middleware for Authentication
Tutorials/Next.js/Creating Middleware
▲Next.js

Creating Middleware

Updated 2026-04-20
2 min read

Creating Middleware

Middleware in Next.js allows you to run code before a request is completed, enabling you to modify requests and responses. This feature is particularly useful for tasks such as authentication, logging, rate limiting, and more. In this tutorial, we'll explore how to create and use middleware in your Next.js applications.

Introduction to Middleware

Middleware functions are executed sequentially, allowing you to chain multiple middlewares together. Each middleware can decide whether to proceed to the next middleware or terminate the request-response cycle. This makes middleware a powerful tool for handling common tasks across your application.

Setting Up Middleware

To use middleware in Next.js, you need to create a middleware.js file at the root of your project. This file will export a default function that handles incoming requests.

Step 1: Create the Middleware File

First, create a middleware.js file in the root directory of your Next.js project:

// middleware.js

export default function middleware(req, ev) {
  // Your middleware logic here
}

Step 2: Define Middleware Logic

The middleware function receives two arguments: req (the request object) and ev (an event object). You can use these objects to inspect and modify the request.

Here's a simple example of a middleware that logs the incoming request URL:

// middleware.js

export default function middleware(req, ev) {
  console.log(`Request received for: ${req.url}`);
  return NextResponse.next();
}

Step 3: Use NextResponse to Control Flow

The NextResponse object is used to control the flow of requests. You can use it to modify the response or terminate the request.

Here's an example of a middleware that redirects users to a different page if they are not authenticated:

// middleware.js

import { NextResponse } from 'next/server';

export default function middleware(req) {
  const isAuthenticated = checkAuthentication(req);

  if (!isAuthenticated) {
    return NextResponse.redirect(new URL('/login', req.url));
  }

  return NextResponse.next();
}

function checkAuthentication(req) {
  // Implement your authentication logic here
  return false;
}

Advanced Middleware Usage

Chaining Multiple Middlewares

You can chain multiple middlewares by exporting an array of middleware functions in the middleware.js file:

// middleware.js

import { NextResponse } from 'next/server';

const logMiddleware = (req) => {
  console.log(`Request received for: ${req.url}`);
  return NextResponse.next();
};

const authMiddleware = (req) => {
  const isAuthenticated = checkAuthentication(req);

  if (!isAuthenticated) {
    return NextResponse.redirect(new URL('/login', req.url));
  }

  return NextResponse.next();
};

export default [logMiddleware, authMiddleware];

Conditional Middleware

You can apply middleware conditionally based on the request path or other criteria:

// middleware.js

import { NextResponse } from 'next/server';

export default function middleware(req) {
  if (req.url.startsWith('/admin')) {
    const isAdmin = checkAdmin(req);

    if (!isAdmin) {
      return NextResponse.redirect(new URL('/', req.url));
    }
  }

  return NextResponse.next();
}

function checkAdmin(req) {
  // Implement your admin check logic here
  return false;
}

Best Practices

  1. Keep Middleware Lightweight: Middleware should perform minimal operations to avoid introducing performance bottlenecks.
  2. Error Handling: Always handle errors gracefully within middleware to prevent unhandled exceptions.
  3. Security Considerations: Be cautious with sensitive data and ensure that middleware does not expose security vulnerabilities.
  4. Testing: Write unit tests for your middleware to ensure it behaves as expected under different scenarios.

Conclusion

Middleware in Next.js provides a powerful way to handle common tasks across your application. By following the steps outlined in this tutorial, you can create robust middleware functions to enhance the functionality and security of your Next.js applications. Remember to keep your middleware lightweight and secure, and always test thoroughly to ensure it works as expected.


PreviousMiddleware FunctionsNext Using Middleware for Authentication

Recommended Gear

Middleware FunctionsUsing Middleware for Authentication