In my backend (NodeJS / JavaScript) I would like to set an HttpOnly cookie that keeps track of the JWT refresh token.
I'm using Koa to communicate with the frontend.
As you can see I set the cookie with ctx.cookies.set()
, which does seem to work in the browser inspector. But not when I try to retrieve the cookie by logging it with console.log(ctx.cookies.get("jwt"));
, then it's undefined.
Code:
const login = async (ctx) => {
const { email, password } = ctx.request.body;
const session = await userService.login(email, password);
ctx.body = session[0];
ctx.cookies.set("jwt", session[1], {
httpOnly: true,
});
console.log(ctx.cookies.get("jwt")); // is undefined
};
login.validationScheme = {
body: {
email: Joi.string().email(),
password: Joi.string(),
},
};
The refresh call I'd like to use the cookie in:
const refresh = async (ctx) => {
const session = await userService.refresh(ctx.cookies.get("jwt")); // is undefined
ctx.body = session;
};
Browser:
Set-Cookie in browser is set correctly:
Screenshot of browser api-call response (Set-Cookie)
Cookies-section in browser is empty though:
Screenshot of browser Cookies
Right after I set the cookies I try to console.log(ctx.cookies.get("jwt"));
the cookies to make sure it worked but it turns out it's undefined. Of course I don't need the cookies right away after I've set them. But I need it when I call the refresh api-call.
Please do not close my question but instead ask additional questions if you need them.
Maybe someone could explain to me how to use the JWT token with cookies some more, maybe I'm not getting it right?
Thanks!
I've tried everything I found online but there's not much help containing Koa and cookies. So I really hope someone could help me here.