JWT tokens help keep users logged in safely. They store user info in a secure way so the server can check who you are without asking every time.
0
0
JWT token creation in Express
Introduction
When you want users to log in once and stay logged in while using your app.
When you need to send user identity safely between client and server.
When building APIs that require user authentication.
When you want to avoid storing session data on the server.
When you want a simple way to verify user permissions.
Syntax
Express
const jwt = require('jsonwebtoken');
const token = jwt.sign(payload, secretKey, options);payload is the user data you want to include in the token.
secretKey is a secret string only your server knows to sign the token.
Examples
Creates a token with user ID 123 using a secret key.
Express
const token = jwt.sign({ userId: 123 }, 'mySecretKey');Creates a token that expires in 1 hour.
Express
const token = jwt.sign({ userId: 123 }, 'mySecretKey', { expiresIn: '1h' });Creates a token with user role and specifies the signing algorithm.
Express
const token = jwt.sign({ userId: 123, role: 'admin' }, 'mySecretKey', { algorithm: 'HS256' });Sample Program
This Express server has a /login route. When you send a username in JSON, it creates a JWT token with that username and sends it back. The token expires in 2 hours.
Express
import express from 'express'; import jwt from 'jsonwebtoken'; const app = express(); app.use(express.json()); const SECRET_KEY = 'superSecret123'; app.post('/login', (req, res) => { const { username } = req.body; if (!username) { return res.status(400).json({ error: 'Username required' }); } // Create a token with username and expiry of 2 hours const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '2h' }); res.json({ token }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Always keep your secret key safe and never share it publicly.
Tokens can include expiration to improve security.
Use HTTPS to protect tokens during network transfer.
Summary
JWT tokens store user info safely for authentication.
Use jwt.sign() with a payload and secret key to create tokens.
Set token expiration to limit how long tokens are valid.