Reputation: 529
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.
}
Upvotes: 28
Views: 40422
Reputation: 11
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 });
}
Upvotes: 0
Reputation: 2139
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');
}
}
Upvotes: 39
Reputation: 69
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);
}
}
Upvotes: 2
Reputation: 529
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());
};
Upvotes: 10
Reputation: 81
You might want to just extract it from a location:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
Upvotes: -5