Search code examples
reactjsnext.jsnext-router

How to redirect to root if the query param is not defined?


I wanna to redirect my website to the home / if the is no query param is defined. I am building a search website with nextjs is which / is the home and /search is the search page. I am passing the query term in the URL as /search?query=myterm. when a user tries to access the /search without the query I wanna to redirect the user the home /. But how can I do that?


Solution

  • Make use of the redirects mechanism: https://nextjs.org/docs/api-reference/next.config.js/redirects

    You can read the value of query params like this:

    module.exports = {
      async redirects() {
          {
            source: '/specific/:path*',
            has: [
              {
                type: 'query',
                key: 'page',
                value: 'home',
              }
            ],
            permanent: false,
            destination: '/:path*/:page',
          },
      }
    }