Search code examples
javascriptreactjsnext.jsparameters

Next.js params undefined


I am trying to get the endpoint from a page in my Next.js application using the url parameters, but it keeps coming back undefined even though I can see the endpoint in the browser.

I have tried using usePathname from next/navigation, and that works but this requires usage in a Client Component, which I can't do because I need to use async/await for the component because it is fetching data from a database.

In app/category/[id]/page.tsx:

const CategoryPage = async (props: Props, { params }) => {
  ...
  let notes = await getNotes(params.id);
}

The getNotes function is a request function in a utils folder which fetches my api route at app/api/[id]/route.ts.

I have also tried changing the file structure for the api route to include "category" like this: app/api/category/[id]/route.ts, but this had no effect.

I start the app with npm run dev. When I try to access the category page, the expected path shows in the browser, but it instead loads the error page that says params is undefined.


Solution

  • From Next.js - Dynamic Routes:

    const CategoryPage = async ({ params }: { params: { id: string } }) => {
      // ...
      let notes = await getNotes(params.id);
      // ...
    }
    

    params would be provided in the first function argument.