Dynamic API endpoint to fetch details of a specific _id from mongoDB
Unanswered
yupitsadi posted this in #help-forum
![Avatar](https://cdn.discordapp.com/avatars/743393751833247746/46bd32f5f3c6b8cee773ba1d72d9e09b.webp?size=256)
1. Dynamic Route Segment:The file path [id] within your API route directory (/src/app/api/workshop/[id]/route.ts) signifies a dynamic route segment.
2. Accessing the id Parameter:
Console error - "
2. Accessing the id Parameter:
import { NextRequest, NextResponse } from 'next/server';
import { connectDB } from "@/lib/mongodb";
import { workshop } from "@/models/Workshop";
export async function GET(
request: NextRequest,
context: { params: { id: string } }
) {
try {
const { id } = context.params;
await connectDB();
const workshopData = await workshop.findById(id);
if (!workshopData) {
return new Response('Workshop not found', { status: 404 });
}
return NextResponse.json(workshopData);
} catch (error) {
console.error('Error fetching workshop:', error);
return new Response('Internal Server Error', { status: 500 });
}
}
Console error - "
> workshops@0.1.0 build
> next build
▲ Next.js 15.1.5
- Environments: .env.local, .env.production
Creating an optimized production build ...
✓ Compiled successfully
Linting and checking validity of types ..Failed to compile.
src/app/api/workshop/[id]/route.ts
Type error: Route "src/app/api/workshop/[id]/route.ts" has an invalid "GET" export:
Type "{ params: { id: string; }; }" is not a valid type for the function's second argument.
" if you need any clarification, kindly req7 Replies
![Avatar](https://cdn.discordapp.com/embed/avatars/2.png)
Northeast Congo Lion
so what do u need help again?
![Avatar](https://cdn.discordapp.com/avatars/743393751833247746/46bd32f5f3c6b8cee773ba1d72d9e09b.webp?size=256)
yes sir 🙂
can just explain me how do i proceed ?
![Avatar](https://cdn.discordapp.com/embed/avatars/2.png)
Northeast Congo Lion
ohhhh
![Avatar](https://cdn.discordapp.com/avatars/743393751833247746/46bd32f5f3c6b8cee773ba1d72d9e09b.webp?size=256)
@yupitsadi yes sir 🙂
![Avatar](https://cdn.discordapp.com/embed/avatars/2.png)
Northeast Congo Lion
Update your GET function to use the correct type for the context parameter. Next.js provides proper type definitions, which can be imported as RouteHandlerContext from next/server.
import { NextRequest, NextResponse } from 'next/server';
import { connectDB } from "@/lib/mongodb";
import { workshop } from "@/models/Workshop";
export async function GET(
request: NextRequest,
context: RouteHandlerContext
) {
try {
const { id } = context.params as { id: string };
await connectDB();
const workshopData = await workshop.findById(id);
if (!workshopData) {
return new Response('Workshop not found', { status: 404 });
}
return NextResponse.json(workshopData);
} catch (error) {
console.error('Error fetching workshop:', error);
return new Response('Internal Server Error', { status: 500 });
}
}
corrected code.