I want to create a blog using Next.js 14. I define this function in api/posts/[postSlug]/route.js
. How can I get postSlug
params in this function?
My function code:
// api/posts/[postSlug]/route.js
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
export async function GET (request) {
// const { postSlug } = params;
const postSlug = 'test'
console.log(request);
const post = await prisma.post.findUnique({
where: {
slug: postSlug
}
})
if (post)
return NextResponse.json({
post,
})
return NextResponse.json({
status: 'error',
message: 'not found!'
})
}
You can access the dynamic route parameters of any route handler by accessing the params
object within the second function argument. Here is an example:
// app/items/[slug]/route.ts
export async function GET(
request: Request,
{ params }: { params: { slug: string } }
) {
const { slug } = params;
// ...
}
You can find more about route handlers and all of their abilities inside the official documentation.