NextJS redirect not working (with root and query param)

I have a NextJS app I am attempting to redirect /?s=:search to /search?s=:search.

I have this redirect in my next.config.js, which works locally:

{
  source: '/',
  has: [
    {
      type: 'query',
      key: 's',
    },
  ],
  destination: '/search',
  permanent: false,
},

I’ve tried running locally with next dev, next build && next start, or netlify dev and the redirect works correctly in each case.

When deployed to netlify, however, this specific redirect does not work (other page level redirects do work). I’ve also tried adding a netlify redirect to my netlify.toml, but that didn’t seem to work either:

[[redirects]]
  from = "/"
  to = "/search"
  status = 302
  force = false
  query = {s = ":search"}

I’m not sure if this is an issue with @netlify/plugin-nextjs or if it’s an issue with root-level redirects, or something else entirely.

I’m happy to provide any further details or follow any debug steps you may have.

Thanks!

Hey @eoneill,

To start with, could we know the site name?

The site is currently hosted at https://u-e-r-demo.netlify.app/

Hey @eoneill,

Is the netlify.toml redirect still active? I’m not currently seeing it in our records.

I had removed the netlify.toml redirect (as it wasn’t working either), but have restored it now.

Ideally, I would like the next.config.js redirect to work properly, so I have one source-of-truth for both dev/prod.

Hey @eoneill,

Root-level redirects like these are recommended to be kept in netlify.toml as:

  1. So that they don’t conflict with any other rule
  2. It’s faster

I think you should try using force in the redirect and that should work.

I will try with force and see if that works.

Ideally though, I think this should still work in the next router and this is likely an oversight in the netlify middleware and/or @netlify/plugin-nextjs.

Also, from the docs, it suggests that root-level redirects should be avoided:

Do not add a rewrite from the site root (such as from = "/" ) in netlify.toml or _redirects . Your root-level rewrite would take precedence over the Essential Next.js build plugin’s own rewrites and break routing on your site.
Next.js on Netlify | Netlify Docs

About the warning in the docs, in your case, you explicitly want to do that and thus, that could be a better way to go. Also, since you’re matching the query strings, it’s not going to affect all URLs, just the home page with the specific query string.