Home > other >  How do I get query string params in NextJS middleware
How do I get query string params in NextJS middleware

Time:12-08

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.
}

CodePudding user response:

You might want to just extract it from a location:

const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

CodePudding user response:

As @j-cue said above but I also discovered you can get search from nextUrl.

e.g.

export const middleware = (request) => {
  const { nextUrl: { search } } = request;
  const urlSearchParams = new URLSearchParams(search);
  const params = Object.fromEntries(urlSearchParams.entries());
};
  • Related