Search code examples
javascriptreactjsnext.js

useSearchParams() causes 500 error when page is client side


In a page.tsx, I have something like this:

'use client';

import { AddForm } from '@/components/AddForm';
import { useSearchParams } from 'next/navigation';

export default function Page() {
  const searchParams = useSearchParams();

  console.log(searchParams);

  return <AddForm />;
}

When the app is built, and I load that page, there will be a request sent to: https://localhost:3000/add?_rsc=3b6ew, which will result in 500, reloading the page.

Why does this happen, and how to prevent it? Maybe in Next.js, pages aren't supposed to be client side?

Note: I'm using useSearchParams() in that page because I need the query strings for API requests.


Solution

  • Maybe in Next.js, pages aren't supposed to be client side?

    While page.js/layout.js is 100% valid to be a client component. The overall recommendation from the Next.js team is to keep things in the server until you need a client functionality. If your page doesn't require server stuff e.g. db querying, then You are free to make it a client component.

    When you encounter 500 error, there will be logs in you terminal explaining what went wrong. Please update your question to include that logs.


    You don't need useSearchParams to read query parameters in page.js as Next.js provides them via a prop

    'use client';
    
    import { AddForm } from '@/components/AddForm';
    
    export default function Page({searchParams}) {
      const page = searchParams.page
      const limit = searchParams.limit
    
      console.log(searchParams);
    
      return <AddForm />;
    }