Within my client component called GetUserInfoButton
, I initiate a GET request using the URL format of
http://localhost:3000/test/users/[id]
. The [id]
in this URL is represented by an alphanumeric sequence similar to MongoDb.
My intention within the file app/api/users/[id]/route.ts
is to handle and process this incoming request with the corresponding [id]
. Below is the code snippet for my GetUserInfoButton
component:
'use client';
export default function GetUserInfoButton({ id }: { id: string }) {
const contentType = "application/json";
const handleClick = async (id: string) => {
try {
const res = await fetch(`/api/users/${id}`, {
method: "GET",
headers: {
"Content-Type": contentType,
}
});
if (!res.ok) {
throw new Error(res.status.toString());
}
} catch (error) {
console.log("error ===> ", error);
}
};
return (
<button onClick={() => handleClick(id)}>
Get
</button>
);
}
Furthermore, here is the content of my route.ts
file:
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) {
const id = req.url.split("http://localhost:3000/api/users/")[1];
return NextResponse.json({
success: true,
id: id
}, {
status: 200,
})
}
In the past when utilizing the pages router, I could employ useRouter()
on the client-side to access the id. Now, in the server component context, how can I obtain the id parameter?
It's worth noting that my project is built using Next.js version 13.4.16
.