#get the params of the request

1 messages · Page 1 of 1 (latest)

shut wagonBOT
#

Hi @clever flint. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To get the parameters of a request in Next.js, the approach depends on whether you are using the pages directory or the app directory. Below are the methods for both:

Using the pages Directory

In the pages directory, you can access the parameters of a request using the context parameter in getServerSideProps. The context object contains a params key that holds the route parameters.

Example:

// pages/[id].js

export async function getServerSideProps(context) {
  const { params } = context;
  const id = params.id; // Access the dynamic route parameter

  return { props: { id } };
}

export default function Page({ id }) {
  return <div>Page ID: {id}</div>;
}

For more details, refer to the Next.js documentation on getServerSideProps (https://nextjs.org/docs/pages/api-reference/functions/get-server-side-props#context-parameter).

Using the app Directory

In the app directory, you can access the parameters of a request using the context parameter in your route handler. The context object contains a params key that holds the dynamic route parameters.

Example:

// app/dashboard/[team]/route.ts

type Params = {
  team: string;
};

export async function GET(request: Request, context: { params: Params }) {
  const team = context.params.team; // Access the dynamic route parameter
  return new Response(`Team: ${team}`);
}

For more details, refer to the Next.js documentation on route.js context parameter (https://nextjs.org/docs/app/api-reference/file-conventions/route#context-optional).

By following these methods, you can effectively retrieve the parameters of a request in both the pages and app directories in Next.js.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: