redirect all `*` to specific path in nextjs
Asked Answered
S

2

5

I have a single landing page nextJs application it is possible to redirect all * to specific routes as we do in react-router like this how can I do exactly the same in nextJs

    <BrowserRouter>
      <Routes>
        <Route path={ROUTES.ROOT} element={<Registry />} />
        <Route path={ROUTES.ALL} element={<Navigate to={ROUTES.ROOT} />} />
      </Routes>
    </BrowserRouter>
export const ROUTES = {
  ALL: '*',
  ROOT: '/registry',

};

what I have done so far is that I'm able to redirect a specific route to specific route but not able to redirect all routes to a specific route

const nextConfig = {
  async redirects() {
    return [
      {
        source: '/path', // not able to "*" the route
        destination: '/registry', // Matched parameters can be used in the destination
        permanent: false,
      },
    ];
  },
};

module.exports = nextConfig;
Shanna answered 6/4, 2022 at 15:19 Comment(0)
H
6

Unfortunately, nextJs doesn't seems to have a proper way to handle this kind of redirection inside the nextConfig, But if you want to redirect any 404 page to home, what you can do is:

  1. Create a custom 404 page inside the pages, note that your page must be named as 404
  2. Add this snippet in the 404 file.

import { useEffect } from 'react'
import { useRouter } from 'next/router'
export default function Custom404() {
  const router = useRouter()

  useEffect(() => {
    router.replace('/')
  })

  return null
}

With that any not found route should redirect to home page. See this discussion on github

edit: One last thing, if you want to handle some kind of logic when a user visit some route and redirect if fail, you can do so with getServerSideProps:

  1. Add the async function getServerSideProps in the page where you want to handle some kind of logic before render the page:

// Page where you want to handle the logic
// data is the props that comes from getServerSideProps
function Page({ data }) {
  // Render data...
}


// This gets called on every request
export async function getServerSideProps() {
  // fetch some data from external API
  const res = await fetch(`https://someapi/fetchData`)
  const data = await res.json()
  
  if(!data) {
    // Here we redirect the user to home if get some error at the API
    return {
      redirect: {
        destination: '/',
        permanent: false
      }
    }
  }

  // Otherwise pass the data to Page as props
  return { props: { data } }
}
export default Page

It's just an example but you got the idea, if you want to learn more about this, read the docs here

Homan answered 6/4, 2022 at 16:50 Comment(0)
C
0
{
   source: '/:path*',
   destination: '{SOME_URL}/:path*',
}
Cloraclorinda answered 20/9 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.