Topic 51 of 55
JWT (JSON Web Token) Generation
Overview
JWTs are a secure way to transmit information between parties as a JSON object. In Node.js APIs, they are primarily used for stateless authentication. Instead of storing session IDs in a database, the server signs a token and gives it to the client.
Syntax
javascript
// 1. Install jsonwebtoken
// npm install jsonwebtoken
const jwt = require('jsonwebtoken');
// The secret key must NEVER be exposed publicly. Store it in .env
const SECRET = process.env.JWT_SECRET;
function generateToken(userId) {
// Payload: The data you want to embed in the token
const payload = { id: userId, role: 'admin' };
// Sign the token: Requires payload, secret, and options (like expiration)
const token = jwt.sign(payload, SECRET, {
expiresIn: '1h' // Token becomes invalid after 1 hour
});
return token;
}Common Pitfalls
- Do NOT put sensitive information (like passwords or credit cards) in the JWT payload! The payload is just Base64 encoded, meaning anyone can read it. The signature only proves it hasn't been tampered with.
- If you lose or change your `JWT_SECRET`, all currently issued tokens will immediately become invalid, logging out all users.
Real-World Example
Logging in a user and issuing a token:
example
javascript
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await db.findUserByEmail(email);
if (!user || user.password !== password) { // Assume plaintext pass for simplicity here
return res.status(401).json({ error: "Invalid credentials" });
}
// User is authenticated, generate a JWT
const token = jwt.sign(
{ userId: user._id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
// Send the token back to the client
// The client will store it (e.g., localStorage or cookies)
res.json({ message: "Login successful", token: token });
});