1

Simple question.

/app -/questions -/edit -/[id] -route.ts

I use NextJS 14 with app router and have the following API endpoint.

How to I get the value of "id". For example if query looks like "/questions/edit/312", I should get "312".

Looked over the internet but only found solution for pages router style where you can get it using res.query

1 Answer 1

1

Problem :

How to get Dynamic Segment from URL

Other Problems:

  • According to /app -/questions -/edit -/[id] -route.ts this location of route.ts is wrong because routes are written under folder api app/routeName/api/route.ts
  • So the /app -/questions -/edit -/[id] -route.ts is now considered a page because of file conventions (Read this 1), but you have written route.ts which is wrong.

Possible Solution :

  • If /app -/questions -/edit -/[id] -route.ts this an API endpoint(Route Handler) then move it under api folder, which will be in app folder.

  • Else if /app -/questions -/edit -/[id] -route.ts this is a page, then rename route.ts to page.ts.


Now to get the params [id] :

In page.ts :

export default function Page({ params }: { params: { id: string } }) {
  return <div>Question: {params.id}</div>  // 312
}

Go to url http://localhost:3000/questions/edit/312 to see the output


In route.ts at api/questions/edit/312:

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  const id= params.id  // 312
   return Response.json({ data : id })
}

Go to url http://localhost:3000/api/questions/edit/312 to see the output


Please Read :

If you have any doubts, then please leave a comment (I will update answer if necessary)

Sign up to request clarification or add additional context in comments.

2 Comments

This works, but then what is the purpose of the slug promise described in the docs at nextjs.org/docs/app/building-your-application/routing/… (which doesn't work)
@DJFriar This answer was given during NextJS stable version 13 or 14 something, but now in 15 they are using await. 1. nextjs.org/docs/14/app/building-your-application/routing/… 2. nextjs.org/docs/13/app/building-your-application/routing/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.