Search code examples
javascriptreactjsnext.js

redirect all `*` to specific path in nextjs


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;

Solution

  • 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