skip to Main Content

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


  1. Chosen as BEST ANSWER

    After 2 days of struggle, I finally resolved the issue. Here is an explanation for the same.

    1. useSearchParams() hook, somehow is not working and doesn't give me search Params i.e. userId in my case.

    2. So instead of using useSearchParams() hook, I'm using

    export default FreelancerChat ({ params, searchParams }) {
       const id = params.id;
       const userId = searchParams.userId;
    }

    1. URLSearchParams { } in nextURL seems like it is empty, but it is actually not. So that was a false alarm. You can do

    request.nextUrl.searchParams.get("userId")

    to check if searchParams are set correctly or not.

    1. Also I would suggest having a correct understanding of when to use client components and when to use server components.

    I hope this helps the community as well. Thanks to @codejockie for his time and effort!


  2. 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 is https://localhost:3000/chat when you set the search params like you did, you would expect the new URL to be https://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 call NextResponse.rewrite(request.nextUrl);.

    Using your code, you should have:

    export async function middleware(request: NextRequest) {
      const isAuth = await isLoggedIn();
      const { pathname } = request.nextUrl;
      const isChatWindow = pathname.startsWith("/chat");
      const isFreelancerDashboard = pathname.startsWith("/freelancer-dashboard");
    
      if (!isAuth) {
        return NextResponse.redirect(new URL("/", request.url));
      }
    
      const payload = await getPayload();
    
      if (isChatWindow) {
        request.nextUrl.searchParams.set("userId", payload.ctx.userId);
        // This line ensures the URL is rewritten so the search params becomes available where you want it.
        return NextResponse.rewrite(request.nextUrl);
      }
    
      // Continue processing if no condition is met
      return NextResponse.next();
    }
    
    export const config = {
      matcher: ["/freelancer-dashboard/:path*", "/chat/:path*"],
    };
    

    I hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search