#Working with cookies
8 messages · Page 1 of 1 (latest)
🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord
🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize
✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)
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
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;