Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect in Next.js from uppercase to lowercase URL

I need to redirect visitors from /Contact to /contact.

When I am doing it as described in the docs I get an infinite redirect loop.

This is what I tried:

// next.config.js
async redirects() {
    return [
        {
            source: '/Contact',
            destination: '/contact',
            permanent: true
        }
    ]
}
like image 574
Yuval Levy Avatar asked Sep 01 '20 21:09

Yuval Levy


2 Answers

With Next.JS 12 you can now use custom middleware.

Create file named _middleware.js under pages 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(req.nextUrl.origin + req.nextUrl.pathname.toLowerCase());
};

export default Middleware;
like image 108
ch3rn1k Avatar answered Oct 20 '22 11:10

ch3rn1k


The following will redirect all paths that don't exist to a lower case path. If the path is not found, it will show a 404.

import { useEffect } from 'react'
import { useRouter } from 'next/router'
import Error from 'next/error'

export default function ResolveRoute() {
  const router = useRouter()

  useEffect(() => {
    const { pathname } = router;

    if (pathname !== pathname.toLowerCase()) {
      router.push(pathname.toLowerCase())
    }
  },[router])

  return <Error statusCode={404} />
}

Putting this file name as "[route].js" in the root of your pages folder will act as a catch all (unless the page exists). This will redirect to lower case. If already ready lower case then it means the page is a 404.

like image 42
Andrew Avatar answered Oct 20 '22 13:10

Andrew