Make NextJS <Link> respect the default "Redirects" middleware

931 Views Asked by At

I'm using React and NextJS version 12 and want to redirect these two URLs:

  • http://localhost:3000
  • http://localhost:3000/

Both should go to

  • http://localhost:3000/dashboard

I have the following Redirects middleware set up:

async redirects() {
  return [
    {
      source: '/',
      destination: '/dashboard',
      permanent: false,
    },
  ];
},

This works if I type either URL above in my address bar. However, this does not work:

<Link href="/">dashboard</Link>

This will instead send me to the index.tsx at the root (a fallback page, just in case we'd ever need it) at the URL http://localhost:3000. It should redirect to http://localhost/dashboard.

Perhaps I'm confused about what runs on the server versus on the client? I come from Angular where the routes and redirects are for client (or both, when using SSR, I believe).

How do I make the Link respect the built in Redirects middleware from NextJS? Or is my only option to write custom middleware?

1

There are 1 best solutions below

0
On

A solution is to add an UseEffect on your index.tsx:

import React, { useEffect } from "react";
import Router from "next/router";

const Home = (props: any) => {
  useEffect(() => {
    const { pathname } = Router;
    if (pathname === "/") {
      Router.push("/dashboard");
    }
  });
  return <></>;
};

export default Home;