avatarKhoa Pham

Summary

Next.js handles route case sensitivity by default, but developers can enforce lowercase routes using a middleware.

Abstract

In Next.js, the default behavior treats routes as case sensitive, meaning that localhost:3000/About and localhost:3000/about are considered distinct paths. To standardize on lowercase routes, developers can implement a middleware by creating a middleware.tsx file within the src directory, at the same level as the pages directory. This middleware checks if the current pathname is already in lowercase and

How to handle route case sensitivity in Nextjs

By default, Nextjs route is case sensitive, so localhost:3000/About and localhost:3000/about are different routes.

To make uppercase routes become lowercase routes, we can add a middleware.tsx file to the src so it is same level as pages

import { NextResponse, NextRequest } from "next/server"
const Middleware = (req: NextRequest) => {
    if (req.nextUrl.pathname === req.nextUrl.pathname.toLowerCase()) {
        return NextResponse.next()
    }
    return NextResponse.redirect(
        new URL(req.nextUrl.origin + req.nextUrl.pathname.toLowerCase())
    )
}
export default Middleware
Nextjs
Middleware
Case Sensitive
Route
React
Recommended from ReadMedium