I've developed a website using Next.js 13 with a route called /api/users/me
. In this route, I need to access the cookies to extract the token. While calling the API from the browser gives me the desired result, trying to call it from the frontend page returns null for the cookies.
In src/api/users/me/route.js
import { NextResponse, NextRequest } from "next/server";
import { connectDB } from "@/dbConfig/dbConfig";
connectDB();
export async function GET(request) {
try {
console.log("Token is: ", request.cookies); // Expecting to receive cookies but get null
return NextResponse.json({ msg: "success" }, { status: 200 });
} catch (error) {
return NextResponse.json(
{ msg: "can't get data", err: error.message },
{ status: 500 }
);
}
}
In src/app/profile/page.jsx
import UserDetails from "@/components/UserDetails";
import { cookies } from "next/headers";
async function getData() {
const cookieStore = cookies();
const token = cookieStore.get("token"); // Able to retrieve the cookies here
try {
console.log(token.value);
const res = await fetch(`http://localhost:3000/api/users/me`, {
headers: {
userToken: String(token.value), // Trying to pass it in the headers
},
});
if (!res.ok) {
throw new Error("Failed to fetch data, please try another time");
}
return res.json();
} catch (error) {
console.log("Error loading topic", error);
}
}
async function ProfilePage() {
const data = await getData();
return (
<div className="flex flex-col justify-center items-center min-h-screen">
<h1 className="font-bold text-3xl">Profile page</h1>
<p className="text-gray-600">This is the profile page</p>
<UserDetails />
</div>
);
}
export default ProfilePage;