Facebook Pixel

How does JWT work in Node.js?

On login, sign a token with jwt.sign({ userId }, secret, { expiresIn }). Store in an httpOnly cookie. On each request, verify with jwt.verify(token, secret) in an auth middleware. Set req.user from the payload. Logout clears the cookie. The server is stateless; no session store needed.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How JWT Works in Node.js: Step by Step

header.payload.signature. Header is base64url-encoded JSON with the algorithm. Payload is base64url-encoded JSON with claims (userId, role, exp). Signature is HMAC of header.payload using your secret, proving the token was not tampered with.

In an httpOnly, secure, sameSite cookie for web apps. The browser sends it automatically. In secure storage (Keychain, Keystore) for mobile. Do not use LocalStorage (open to XSS).

Read the token from req.cookies.token or the Authorization header. Call jwt.verify(token, process.env.JWT_SECRET). It checks the signature and expiry. If valid, set req.user from the payload and call next. If not, return 401.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.