Sign Token Using Cookie and LocalStorage

Sabbir Mohammad Sami
Sabbir Mohammad Sami
March 30, 2025·12 min read

Share:

Sign Token Using Cookie and LocalStorage

Sign Token Using Cookie and LocalStorage

Sign Token Using Cookie

Client-Side

I am using Axios to make POST requests to my server for handling JWT for /jwt and logout /logout.

When a user logs in:

          
axios .post( `https://server.vercel.app/jwt`, { email: currentUserEmail }, // Assuming the server expects an object with an 'email' property { withCredentials: true, } ) .then((res) => { console.log("JWT creation response:", res.data); }) .catch((error) => { console.error("Error creating JWT:", error); });

When a user logs out:

          
axios .post( "https://server.vercel.app/logout", { email: currentUserEmail }, // Assuming the server expects an object with an 'email' property { withCredentials: true, } ) .then((res) => { console.log("Logout response:", res.data); }) .catch((error) => { console.error("Error logging out:", error); });

Server-Side

Make sure you install jsonwebtoken and cookie-parser in your server:

          
const jwt = require("jsonwebtoken"); const cookieParser = require('cookie-parser');

Use cookie-parser middleware:

          
app.use(cookieParser());

Error Handling in verifyToken Middleware:

          
const verifyToken = (req, res, next) => { const token = req?.cookies?.token; if (!token) { return res.status(401).send({ message: "unauthorized access" }); } jwt.verify(token, process.env.TOKEN_SECRET, (err, decoded) => { if (err) { return res.status(401).send({ message: "unauthorized access" }); } else { req.user = decoded; next(); } }); };

JWT Route (/jwt):

          
app.post("/jwt", async (req, res) => { try { const user = req.body; const token = jwt.sign(user, process.env.TOKEN_SECRET, { expiresIn: "2h", }); res.cookie("token", token, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: process.env.NODE_ENV === "production" ? "none" : "strict", maxAge: 2 * 60 * 60 * 1000, // 2 hours in milliseconds }).send({ success: true }); } catch (error) { console.error("Error creating JWT:", error); res.status(500).send({ success: false, message: "Internal Server Error" }); } });

Logout Route (/logout):

          
app.post("/logout", async (req, res) => { const user = req.body; console.log("logging out", user); res.clearCookie("token", { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: process.env.NODE_ENV === "production" ? "none" : "strict", }).send({ success: true }); });

SameSite Attribute for Cookies:

In your /jwt route, if you're setting sameSite: "none" for the cookie, ensure your production environment uses HTTPS because the "none" value for sameSite requires a secure connection.

          
sameSite: process.env.NODE_ENV === "production" ? "none" : "strict",

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(); }); }

Common Interview Questions Related to JWT

  1. What is JWT?

    JWT stands for JSON Web Token. It is a compact, URL-safe means of representing claims to be transferred between two parties.

  2. How is a JWT structured?

    A JWT consists of three parts: Header, Payload, and Signature.

  3. What is the purpose of the JWT Header?

    The Header describes how the JWT is encoded and signed, including the type of token (JWT) and the signing algorithm being used.

  4. What are the typical use cases for JWT?

    JWTs are commonly used for authentication and information exchange in web development and APIs.

AuthenticationFrontendDevelopment

More Related Blogs