Sign Token Using Cookie and LocalStorage
There are two common places to keep a JSON Web Token in the browser. An httpOnly cookie set by the server travels with every request sent withCredentials and cannot be read by page scripts, but needs sameSite "none" over HTTPS in production. In localStorage, the client keeps the token itself and sends it in the Authorization header.


Sign Token Using LocalStorage
Client-Side
The code begins with a conditional statement checking if the variable email has a truthy value. If the email is truthy, the block of code inside the if statement will be executed:
if (email) {
fetch('https://server.vercel.app/user/{email}', {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(currentUser),
})
.then((res) => res.json())
.then((data) => {
const accessToken = data.token;
console.log(accessToken);
localStorage.setItem("accessToken", accessToken);
setToken(accessToken);
});
}Server-Side
Verify JWT Middleware:
function verifyJWT(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send({ message: "Unauthorized access" });
}
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.WEB_TOKEN, function (err, decoded) {
if (err) {
return res.status(403).send({ message: "Forbidden access" });
}
req.user = decoded;
next();
});
}