Search code examples
typescriptnext.jssupabase

How to use Dynamic Route in Server Side component with Supabase in Next.js?


export default async function Page({
  searchParams,
}: {
  searchParams?: { [key: string]: string | string[] | undefined };
}) {
  // const searchParams = useSearchParams();
  const id = searchParams?.p ?? "aaa"; // default value is "1"
  console.log(id);

  const supabase = createClient();
  const { data, error } = await supabase
    .from("book")
    .select()
    .eq("id","asjiofeowef");

  console.log(data);

  return (
    <>
      <div className="bg-black md:p-5 md:flex">
        <div className="aspect-w-16 aspect-h-9 w-full md:w-8/12">
          <Youtube />
        </div>
        <div className="w-full md:w-4/12 p-5">
        </div>
      </div>
    </>
  );
}

I have this file under app/books/page.tsx. And I want to get the id of the book using the dynamic route not the params.

I've been reading about getServerSideProps and most information about this did not work for some reasons. Either I got "getServerSideProps" is not supported in app/. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching error or satisfies GetServerSideProps · ────┬──── ────────────────── · ╰── This is the expression part of an expression statement

I even copied and pasted the example from Nextjs app and did not work.

My question is


Solution

  • Based on your example you can create the following route inside your folder structure: /app/books/[id]/page.tsx. Inside your page you can then access the property the following way:

    interface Props {
      params: { id: string };
    }
    
    export default async function Page({ params }: Props): Promise<JSX.Element> {
      const { id } = params;
      return <>ID: {id ?? "1"}</>;
    }
    

    Please note that you should do some research on your own before posting to stack overflow. A look at the app router documentation here would've probably sufficed.