Next.js Discord

Discord Forum

question on Api routes

Answered
Japanese Bobtail posted this in #help-forum
Open in Discord
Avatar
Japanese BobtailOP
i have created API route like api/trend/[slug]/route.ts
The url is this : http://localhost:3000/api/trend/test?time=1h

I wanted to use both dynamic route and parameters so my code looks like below. I refereed to next docs, Any suggestionst to improve this code ? i am not sure why I need request and param object separate.

export async function GET(req: Request, { params }: { params: { slug: string } }) {

    const { searchParams } = new URL(req.url)
    const time = searchParams.get('time')
    const slug = params.slug;

    if (!slug) return new Response(null, { status: 500 });
.
Answered by Risky
That looks like the recommended method... Personally I like how it makes it clear that is from the dynamic route... Also you shouldn't need to create a new url, as you can use [nextUrl](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#url-query-parameters)
View full answer

2 Replies

Avatar
Risky
That looks like the recommended method... Personally I like how it makes it clear that is from the dynamic route... Also you shouldn't need to create a new url, as you can use [nextUrl](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#url-query-parameters)
Answer
Avatar
Japanese BobtailOP
Thanks for the suggestion on nextURL.