I am working on a website that allows Student and Faculty Login. So far, only the student login part generates a JWT and I am trying to reach the protected route /student
. You can check out the code here:
https://github.com/shivpreet16/event-junction
I am sending the JWT generated upon matching credentials in the response header from /api/submit.js
as:
if (auth.checkPass(rowvals[0].stu_pass, data)) {
const token=({
token: jwt.sign(
{
username: rowvals[0].stu_email,
admin: true,
},
KEY
),
});
// console.log(token)
res.setHeader('Content-Type', 'application/json')
res.setHeader('Authorization', token)
res.setHeader("Set-Cookie",'token=${token}; Max-Age=604800; SameSite=Strict');
res.setHeader("Path", '/student' );
// res.status(200).json({ message: "Login successful" });
res.send(JSON.stringify({ message: 'Logged in'}))
} else res.send(JSON.stringify({ message: "Wrong Password" }));
} else {
res.send(err.message);
}
Then, I receive the JWT from the response header at client-side in /components/Login.js
, and try to set it in a cookie using setTokenCookie(token)
function in the /utils/auth.js
file.
const token = response.headers.get('Authorization')
if(token){
console.log("Login successful")
setTokenCookie(token)
console.log(getTokenCookie())
router.push(response.headers.get('Path'))
}
else{
const info = await response.json()
console.log(info.message)
}
However, getTokenCookie()
function (also in /utils/auth.js
) keeps returning null
. I know the JWT token is reaching the client-side from response header as it logs Login successful
. However, the cookie is null.
Kindly help