skip to Main Content

I have the below function in app/api/hello/[slug]/route.ts

when I console log I get undefined . why ???

app/api/hello/[slug]/route.ts

export async function GET({ params }: any) {
    console.log(params);
}

log

- wait compiling /api/hello/[slug]/route (client and server)...
- event compiled successfully in 308 ms (65 modules)
undefined

enter image description here

2

Answers


  1. Because you are destructuring the Request object (which has no params key)

    The parameters object is the second argument.

    export async function GET(request: Request, { params }: { params: { slug: string } }) {
      console.log(request.url, params);
    }

    You may have a look at the NextJS documentation about Dynamic Route Segments:
    https://nextjs.org/docs/app/building-your-application/routing/router-handlers#dynamic-route-segments

    Login or Signup to reply.
  2. It is because first param is Request

    export async function GET(request: Request) {}
    

    And params is 2nd param (optional)

    export async function GET(request: Request, { params }: any) {}
    

    So the final code should be:

    export async function GET(request: Request, { params }: any) {
        console.log(params);
    

    You can make it specific by specifying the type of slug

    export async function GET(request: Request, { params }: { params: { slug: string } }) {
      console.log(params);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search