Home > OS >  How to make URL path case insensitive - NextJs/JS
How to make URL path case insensitive - NextJs/JS

Time:09-22

I am using NextJs and I want to make my URL's case insensitive. Currently due to the fact I am fetching my paths from an API all my paths start with a capital letter. For example www.mysite.com/About. I want the /About to redirect to the same page regardless of whatever case each letter is put in.

Example: Is there an Easy way to have

  • /About
  • /about
  • /aBoUT

All redirect to the same page?

Within my website I have CSR, SSR and SSG. So please take that into account. Furthermore, Id prefer to avoid middleware's if that's at all possible.

I have seen some talk on NextJs redirects function but haven't really gotten a good explanation of how to do the above as of yet. That is my preferred solution.

CodePudding user response:

You can standardize your output from your API to lowercase using

.toLowerCase()

on your string output.

CodePudding user response:

If you are only want that for one or a few pages you can use rewrites elegantly

{
        source: '/(a|A)(b|B)(o|O)(u|U)(t|T)',
        destination: '/about',
}

Rewrite accepts some regex patterns but the "to lowercase" regex expression don't seems to be one of them (at least I couldn't)

You can always generate the rewrites at build time ( I don't recommend more than a middleware only if you have a few pages and performance is super sensitive )

Can you add your reasons to not use a middleware ? Middleware seems the way to go: If you are using Next.JS >=12 you can use custom middleware.

Create file named middleware.js under root folder and use this code:

import { NextResponse } from 'next/server';

const Middleware = (req) => {
  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;
  • Related