Search code examples
restnext.jsbackend

Next js Api routing


I am working with Next js 13.4 and trying to send id of a product with query parameters as - http://localhost:3000/api/abc/abc/update/89?id=2

The code i wrote-

export async function PUT(req,res){
  console.log(req.query);
  return NextResponse.json('hi');
}

I am getting response perfectly but I want to log id from url and I tried using - const {id} = req.query but it shows cannot destructure id as it is undefined. Is there any way I can get that id? Without splitting the url. Main thing is I want to know why req.query is giving undefined? It should give 2.


Solution

  • Route handlers in the App router function differently compared to the previous pages API.

    You've written:

    export async function PUT(req, res) {
    

    Note that the second parameter should be the context rather than the response object.

    Backing to your original question on how to access query parameters in the app router, you can achieve this using either of the following methods:

    1:

    const searchParams = req.nextUrl.searchParams;
    const id = searchParams.get("id");
    

    2:

    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');