29

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

5 Answers 5

40

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');
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

10

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());
};

1 Comment

2

As of Next.js 13.4 you can get search params like this from the url:

export const GET = async (request, { params }) => {
   try{
        
        // Path Params are received from {params} variable
        //You can receive search params as below:
        // UrlPath = `/api/prompt/${post._id.toString()}?type=DELETE`
        //The search params [type, method] for above url

        const {type, method} = Object.fromEntries(request.nextUrl.searchParams);
        console.log(type, method);
        if(type === "DELETE" && method === "GET"){
            //Perform an action
        }

        return new Response("Action performed", {status: 200});
   }
   catch(err){
    console.log(err);
   }
}

1 Comment

0

Try this one :

export async function GET(req: Request, route: { params: { id: 
string } }) {
const id: number = Number(route.params.id);
return new Response(JSON.stringify({ id }), { status: 200 });
}

1 Comment

this is a code only answer. While it may be a good or even the best answer, you can help future readers and the appreciation for your answer by adding an explanation to it.
-5

You might want to just extract it from a location:

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

2 Comments

The question was specifically about NextJS middleware, so this answer using window.location.search doesn't work.
irrelevant to question -1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.