Using Dynamic Routes with Vercel Functions?

Seems like there should be a way to do this... For the route /api/events/init/[key] I have this code:
import { useParams } from 'next/navigation';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export function GET(request: Request) {
const { key } = useParams();

if (key !== process.env.INITIALIZATION_KEY) {
return new Response('Invalid key', { status: 403 });
}

return new Response(`Keys match!`);
}
import { useParams } from 'next/navigation';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export function GET(request: Request) {
const { key } = useParams();

if (key !== process.env.INITIALIZATION_KEY) {
return new Response('Invalid key', { status: 403 });
}

return new Response(`Keys match!`);
}
This results in the error:
You're importing a component that needs useParams. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
You're importing a component that needs useParams. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
Seems like there should be a way to use dynamic routes in Vercel Functions, right? What am I doing wrong?
4 Replies
Neto
Neto5mo ago
you can only use useParams on client side to get the param on the api, use accept a second param on get
// app/api/events/init/[key]/route.ts
export async function GET(
request: Request,
{ params }: { params: { key: string } }
) {
const key = params.key // 'a', 'b', or 'c'
}
// app/api/events/init/[key]/route.ts
export async function GET(
request: Request,
{ params }: { params: { key: string } }
) {
const key = params.key // 'a', 'b', or 'c'
}
njbair
njbairOP5mo ago
Thank you for that. Even now having learned this, it seems like the Vercel docs are unclear about this (or maybe plain wrong). It looks like they're saying that 2nd context parameter is not supported in Next.js:
njbair
njbairOP5mo ago
No description
njbair
njbairOP5mo ago
Want results from more Discord servers?
Add your server