0

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.

1

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

You can standardize your output from your API to lowercase using

.toLowerCase()

on your string output.

1 Comment

yes but I am not really looking for this. I am looking more for using the redirect feature in NextJs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.