Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the query string from a dynamic API routes in NextJS?

Tags:

axios

next.js

I have a file API structure as such: app/api/workspaces[id]/route.js

export async function GET(req: NextApiRequest) {
  console.log("CATEGORY ID", req.query);
  try {
    // I simplified this part, but in the project, I'm fetching the data using Prisma to Supabase
    const tasks = [];
    return NextResponse.json(tasks, { status: 200 });
  } catch (err) {
    return NextResponse.json(
      { message: `Could not fetch workspaces: ${err}` },
      { status: 500 },
    );
  }
}

And I'm calling this API from my FE:

  const { data: tasks, isLoading: isTasksLoading } = useQuery({
    queryKey: [`tasks-${params.id}`],
    queryFn: async () => {
      const response = await axios.get(`/api/workspaces/${params.id}`);
      return response.data;
    },
  });

In route.js I tried to console.log(req.query) but I'm getting undefined. What am I missing?

UPDATE

Turns out, I have to use the second argument of the GET method as such:

export async function GET(req, context: any) {
    const { id } = context.params;
}

I am however, not too sure what's the type of this context

like image 452
Owenn Avatar asked Nov 18 '25 15:11

Owenn


1 Answers

In the app router, as you can read on the doc, Next.js passes to API handler a second object as parameter, which contains a params key where the slug will be.

But you should specify the type yourself. Also, the type of the request passed is NextRequest, not NextApiRequest (the type used for API routes in the pages router):

// app/api/workspaces[id]/route.js

import { NextRequest } from "next/server";

export async function GET(
  request: NextRequest,
  context: { params: { id: string } }
) {
  const { id } = context.params;
}
like image 53
yousoumar Avatar answered Nov 21 '25 05:11

yousoumar