DEV Community

Cover image for Middlewares in Next JS
Jayant
Jayant

Posted on

1 1

Middlewares in Next JS

Middleware in Next.js

Middlewares are code that runs before / after your request handler.

Commonly used for

  • Analytics
  • Authentication
  • Redirecting [ In an Express App it is not applicables, cuz Express runs in backend ]
  • Modifying the request/response

How

Create an middleware.ts, in the top level of yourfresh Next.js app.
You can only one have one middleware.ts where all your middlewares are defined. But you can still organize your middleware logic modularly & then importing them in middleware.ts file.

A Simple Middleware to count the number of Visitors on your site -

// This code will run on every request
import { NextRequest, NextResponse } from "next/server";

let requestCount = 0;
// Simply Define a function named middleware that takes req as parameter.
export default function middleware(req: NextRequest) {
    requestCount++;
    console.log("Number of Requests", requestCount);
    return NextResponse.next();
}
Enter fullscreen mode Exit fullscreen mode

But there is a problem.
Every time we visit the app the count get increased by many times, not 1. This is because Next.js made many request which will cause counter to increase many times.

For Example this request
Network Tab

)

There are 2 ways to avoid this

  1. Using Custom Matchers Matcher allows you to filter Middleware to run on specific paths.
   export const config = {
    matcher: ["/api/:path*", "/"],
    // matcher: "/api/:path*",
   };
Enter fullscreen mode Exit fullscreen mode
  1. Using Conditional Rendering
   export default function middleware(req: NextRequest) {
    //if (req.nextUrl.pathname === "/") {
    //  requestCount++;
    //  console.log("Number of Requests", requestCount);
    //  return NextResponse.next();
    //}
    if (
        req.nextUrl.pathname.startsWith("/") ||
        req.nextUrl.pathname.startsWith("/services")
    ) {
        requestCount++;
        console.log("Number of Requests", requestCount);
        return NextResponse.next();
    } else if (req.nextUrl.pathname.startsWith("/admin")) {
        if (req.body.name !== "Jayant") {
            return NextResponse.redirect(new URL("/", req.url));
        } else {
            return NextResponse.next();
        }
    } else {
        NextResponse.next();
    }
   }
Enter fullscreen mode Exit fullscreen mode

Ref : Next JS Middleware

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay