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.
<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*"],
};
</code>
<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*"],
};
</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.