problems setting cookies with { cookies } from "next/headers";
Unanswered
Silver Fox posted this in #help-forum
Silver FoxOP
if ("sessiontoken" in res) {
jar.set(
"sessiontoken",
res.sessiontoken,
defaultCookieOptions
);
}
redirect(redirectUrl);
}
3 Replies
Silver FoxOP
i did a console log and received the sessiontoken but it just doesn't set the cookie for some reason
Where are you trying to set cookies? You can only set cookies in Server Actions or Route Handler.
You can't do this from a Server Component, even if you call a Server Action or Route handler from within a Server Component.
https://nextjs.org/docs/app/api-reference/functions/cookies#setting-a-cookie
You can't do this from a Server Component, even if you call a Server Action or Route handler from within a Server Component.
https://nextjs.org/docs/app/api-reference/functions/cookies#setting-a-cookie
Irish Red and White Setter
Hello, I am facing a similar situation. Using route handlers to set cookies does not work.
Trying to get the cookies return
export async function POST(request) {
const {email, password} = await request.json();
const response = await fetch(`${baseUrl}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email,
password
})
})
const result = await response.json();
if (result.code === 401) {
return NextResponse.json({
code: 401,
message: 'Invalid email or password'
})
}
const cookieStore = await cookies();
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/'
}
cookieStore.set({name: 'token', value: result.token, ...cookieOptions});
cookieStore.set({name: 'refresh_token', value: result.refresh_token, ...cookieOptions});
cookieStore.set({name: 'user', value: JSON.stringify({
"email": result.email,
"full_name": result.full_name,
"id": result.user_id
}), ...cookieOptions});
return NextResponse.json({
code: 200,
message: 'Login successful',
data: result
});
}
Trying to get the cookies return
undefined