Next.js Discord

Discord Forum

Is there a better way to get path param in API

Answered
4:44 posted this in #help-forum
Open in Discord
Let's say i have a route /api/foo/[id]/route.ts what i normally do in a request is
export const GET = (request: NextRequest) => {
  const url = new URL(request.url);
  const id = url.pathname.split("/").pop();
  return NextResponse.json({id});
}

Is there a better way cause this does't seem right to me? I was expecting the
GET = ({param})
to get param like this but it doesn't work.

5 Replies

Broad-snouted Caiman
Answer
Broad-snouted Caiman
Yeah, it should be something like this:
export const GET = (request: NextRequest, { params }: { params: { id: string } }) => {
  const id = params.id
  return NextResponse.json({id});
}
@4:44 So how do i mark this as solved?
Broad-snouted Caiman
Put your cursor above my reply. It will appear 3 dots on the top-right corner. Click on that, then Apps, then Mark Solution.