I am trying to get the cookies in the user api route for getting the userid , but getting undefined|null, even though i have a cookies stored in my browser, i am able to get the cookies in the server components though, is there a diff way of getting cookies in the api routes?
i have tried some methods but they didnt work out:-
export async function GET(req: NextRequest) {
await dbConnect();
const session = cookies().get("session")?.value;
const session_1 = req.cookies.get("session")?.value; //getting undefined
const id = JSON.parse(session as string)?.id;
console.log("id", id); // getting undefined
if (!id)
return NextResponse.json({ message: "User not found" }, { status: 404 });
try {
const user = await User.findById(id);
if (!user) {
const response: ApiResponse = {
message: "User not found",
success: false,
};
return NextResponse.json(response, { status: 404 });
}
const response: ApiResponse = {
message: "User found",
success: true,
data: user,
};
return NextResponse.json(response, { status: 200 });
} catch (error) {
console.error(error);
return NextResponse.json(
{ message: "Something went wrong" },
{ status: 500 }
);
}
}
New contributor
Naveen Basyal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.