Middlewares in Next JS

Jayant - May 15 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .