Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop the query parameters after a redirect with NextJS?

In NextJS, how can I use redirect to turn URL like /page?foo=bar into /page/bar ?

I read https://nextjs.org/docs/api-reference/next.config.js/redirects but couldn't find a solution.

What I have today is:

{
   source: '/page',
   has: [
       { 
          type: 'query',
          key: 'foo'
       }
   ],
   destination: '/page/:foo',
   permanent: true
}

but that make /page?foo=bar into /page/bar?foo=bar.

How can I drop the query ?

Edit:

So I realized that this doesn't event work at all with Netlify.

I tried to follow https://docs.netlify.com/routing/redirects/ but I have the same problem with the query parameters staying.

like image 951
Wonay Avatar asked Jun 23 '21 16:06

Wonay


1 Answers

You can use middleware.

Just parse the query parameter yourself and add redirection.

Store a file _middleware.ts below the pages directory:

export async function middleware(req: NextRequest) {
    const { pathname } = req.nextUrl;
    
    if (// Your-thing ) 
        return NextResponse.redirect(//Your-url);

    return NextResponse.next();
}  

Maybe there is a different way, I don't know, but it doesn't matter.

like image 188
html_programmer Avatar answered Sep 28 '22 07:09

html_programmer