Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get query string params in NextJS middleware

I'm using NextJS middleware and can get the nextUrl object from the request, which includes things like pathname, but how do I get query string parameters from within the middleware? I can see it comes back as part of the string returned by href which I could then parse myself but I was wondering if it is returned in an object of it's own?

e.g.

export const middleware = (request) => {
  const { nextUrl: { query } } = request;
  ...
};

where query equals

{
  param1: 'foo',
  param2: 'bar',
  etc.
}
like image 811
user7409110 Avatar asked Sep 05 '25 03:09

user7409110


1 Answers

nextUrl object already includes searchParams which is a valid URLSearchParams instance.

E.G. usage

export function middleware(req: NextRequest) {
    if(req.nextUrl.searchParams.get('flag')) {
        return NextResponse.rewrite('/feature');
    }
}
like image 119
T.Chmelevskij Avatar answered Sep 08 '25 00:09

T.Chmelevskij