Working with cookies
Unanswered
Labrador Duck posted this in #help-forum
Labrador DuckOP
I am getting cookies as undefined in my API route when I send request from browser but it works fine when I send request from something like Postman.
Next version: 14.1.1
Next version: 14.1.1
7 Replies
Labrador DuckOP
Login(simplified) route
import { nanoid } from "nanoid";
export async function POST(request: Request) {
const email = await request.json();
const expiresAt = new Date();
expiresAt.setTime(expiresAt.getTime() + 14 * 24 * 60 * 60 * 1000); // 14 days
let cookie = `test-auth-token=${nanoid(
32
)};Expires=${expiresAt.toUTCString()};Path=/; HttpOnly=${true}; SameSite=Lax`;
if (process.env.NODE_ENV === "production") {
cookie = `test-auth-token=${nanoid(
32
)};Expires=${expiresAt.toUTCString()};Path=/; HttpOnly=${true}; Secure=${true}; SameSite=Lax`;
}
return Response.json(
{ success: true },
{
headers: {
"Set-Cookie": cookie,
},
status: 200,
}
);
}Now to check auth status I have getUserSession function which call be /api/status routes
/api/status
import { EncryptJWT, base64url, jwtDecrypt } from "jose";
import { nanoid } from "nanoid";
import { cookies } from "next/headers";
import { NextRequest } from "next/server";
const secret = base64url.decode("rsnZit9e4fZ/CXWvj+ReQ/2lXu9cvysGQoZsQGJG9K4=");
export async function GET(request: NextRequest) {
const currentUserToken = cookies().get("current_user")?.value;
const expiresAt = new Date();
expiresAt.setTime(expiresAt.getTime() + 5 * 60 * 1000);
if (currentUserToken) {
const { payload } = await jwtDecrypt(currentUserToken, secret);
return Response.json({ currentUser: payload });
} else {
const authToken = cookies().get("test-auth-token")?.value;
if (!authToken) {
return new Response(null, { status: 403 });
}
const userInfo = {
userId: "JKS",
};
const jwt = await new EncryptJWT(userInfo)
.setProtectedHeader({ alg: "dir", enc: "A128CBC-HS256" })
.setIssuedAt()
.setExpirationTime("1h")
.encrypt(secret);
let cookie = `current_user=${jwt};Expires=${expiresAt.toUTCString()};Path=/; HttpOnly=${true}; SameSite=Lax`;
return Response.json(
{
currentUser: userInfo,
},
{
headers: {
"Set-Cookie": cookie,
},
}
);
}
}Here I am getting cookie as undefined when called from server component....However it is not undefined when /api/status called from POSTMAN. Works completely fine with postman
Labrador DuckOP
getUserSession: This is the function I call in server component to get the current user info
interface AuthUser {
currentUser: {
userId: string;
};
}
const getUserSession = async () => {
const res = await fetch("http://localhost:3000/api/status");
console.log("res", res.status);
if (res.status === 200) {
const resData: AuthUser = await res.json();
return resData;
}
return null;
};
export default getUserSession;
interface AuthUser {
currentUser: {
userId: string;
};
}
const getUserSession = async () => {
const res = await fetch("http://localhost:3000/api/status");
console.log("res", res.status);
if (res.status === 200) {
const resData: AuthUser = await res.json();
return resData;
}
return null;
};
export default getUserSession;
Labrador DuckOP
Update:
If the api route is called from client component it works completely fine....So the error is with server component
If the api route is called from client component it works completely fine....So the error is with server component