Middlwares in next
Note on Middlwares in next
5 min read
Published January 20, 2026
Tech Notes
What are middlewares?
Middlewares are code that runs before / after your request handler.
It’s commonly used for things like
- Analytics
- Authentication
- Redirecting the user

<details>
<summary>Code</summary>
import express from "express";
const app = express();
let requestCount = 0;
app.use(
function middleware(req, res, next) {
requestCount++;
next()
}
);
app.get("/", (req, res) => {
res.send("Hello world");
})
app.get("/requestCount", (req, res) => {
res.json({
requestCount
})
})
app.listen(3000);
</details>

<details>
<summary>Code</summary>
import express from "express";
import jwt from "jsonwebtoken";
const app = express();
//@ts-ignore
async function authMiddleware(req, res, next) {
const token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, "secret");
if (decoded) {
next();
} else {
res.status(401).send("Unauthorised");
}
}
app.get("/", authMiddleware, (req, res) => {
res.send("You are logged in");
})
app.listen(3000);
</details>
middlewares + Next
Ref - https://nextjs.org/docs/app/building-your-application/routing/middleware
Middleware allows you to run code before a request is completed.
Then, based on the incoming request, you can modify the response by
- rewriting
- redirecting
- modifying the request or response headers
- or responding directly.
Use cases
- Authentication and Authorization: Ensure user identity and check session cookies before granting access to specific pages or API routes.
- Logging and Analytics: Capture and analyze request data for insights before processing by the page or API.
Code
Create a request count middleware
- Create an empty NextJS project
npx create-next-app

-
Create middleware.ts in the root folder

-
Add code to track the number of requests
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
let requestCount = 0;
export function middleware(request: NextRequest) {
requestCount++;
console.log("number of requests is " + requestCount);
return NextResponse.next()
}
- Try visiting the website
Code #2
Create a request count middleware to track only requests that start with /api
- Add a dummy API route (
api/user/route.ts)
import { NextResponse } from "next/server";
export function GET() {
return NextResponse.json({
message: "Hi there"
})
}
- Update
middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
let requestCount = 0;
export function middleware(request: NextRequest) {
requestCount++;
console.log("number of requests is " + requestCount);
return NextResponse.next()
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/api/:path*',
}
Selectively running middlewares
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
console.log(request.nextUrl.pathname)
if (request.nextUrl.pathname.startsWith('/admin')) {
return NextResponse.redirect(new URL('/signin', request.url))
}
if (request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.next()
}
}
Ref - https://github.com/code100x/cms/blob/main/src/middleware.ts