I’m using Next.js with app router. In my middleware.ts, I’m setting search params. But when I try useSearchParams() hook in client component, it just returns ReadonlyURLSearchParams {size: 0}
Please help me out where I might be going wrong.
Here is my middleware code.
export async function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
console.log("pathansdjdsk:", pathname);
const isFreelancerDashboard = pathname.startsWith("/freelancer-dashboard");
const isChatWindow = pathname.startsWith("/chat");
const isAuth = await isLoggedIn();
console.log("Inside Middleware!!----------------");
if (!isAuth) {
console.log("Not Authenticated!!!!!");
return NextResponse.redirect(new URL("/", request.url));
}
const payload = await getPayload();
if (isChatWindow) {
console.log("Inside chat window");
request.nextUrl.searchParams.set("userId", payload.ctx.userId);
console.log("use search params ", payload.ctx.userId);
}
// Continue processing if no condition is met
return NextResponse.next();
}
export const config = {
matcher: ["/freelancer-dashboard/:path*", "/chat/:path*"],
};
Please let me know, where I’m going wrong. Thanks in advance!
I’ve tried searching for ways to set search params, but to no luck.
Updates:
Upon trying the solution suggested by @codejockie,
the nextURL gets updated as below. But still the URL search params are empty.
{
href: 'http://localhost:3000/chat/2-1-1?userId=2',
origin: 'http://localhost:3000',
protocol: 'http:',
username: '',
password: '',
host: 'localhost:3000',
hostname: 'localhost',
port: '3000',
pathname: '/chat/2-1-1',
search: '?userId=2',
searchParams: URLSearchParams { },
hash: ''
}
When I try to log window.location.href in component. I get the below URL. I’m trying to access a dynamic route – srcappchat[id]page.tsx
hash : ""
host : "localhost:3000"
hostname : "localhost"
href : "http://localhost:3000/chat/2-1-1"
origin : "http://localhost:3000"
password : ""
pathname : "/chat/2-1-1"
port : "3000"
protocol : "http:"
search : ""
searchParams: URLSearchParams {size: 0}
2
Answers
After 2 days of struggle, I finally resolved the issue. Here is an explanation for the same.
useSearchParams() hook, somehow is not working and doesn't give me search Params i.e. userId in my case.
So instead of using useSearchParams() hook, I'm using
to check if searchParams are set correctly or not.
I hope this helps the community as well. Thanks to @codejockie for his time and effort!
You have this issue because Next is not aware of the change you made to the URL. Let me explain what I mean.
In your
if (isChatWindow) {...}
, say the current URL ishttps://localhost:3000/chat
when you set the search params like you did, you would expect the new URL to behttps://localhost:3000/chat?userId=ctx.userId
. Even though the update happened Next does not know about that change, so in order to "notify" Next of the update you need to callNextResponse.rewrite(request.nextUrl);
.Using your code, you should have:
I hope this helps.