Using JWT (JSON Web Tokens) with Express

📘 Express.js 👁 55 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

JWT (JSON Web Token) is a compact, URL-safe token format that allows you to securely transmit information between client and server.
It is widely used for stateless authentication in REST APIs.


1. Install Required Packages

npm install express jsonwebtoken bcrypt
  • jsonwebtoken – For generating and verifying JWTs

  • bcrypt – For hashing passwords (optional but recommended)


2. Generate JWT on Login

app.js example:

const express = require('express'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt'); const app = express(); app.use(express.json()); const PORT = 3000; const SECRET_KEY = 'mysecretkey'; // Dummy user database const users = [ { id: 1, username: 'admin', password: '$2b$10$...' } // hashed password ]; // Login route app.post('/login', async (req, res) => { const { username, password } = req.body; const user = users.find(u => u.username === username); if (!user) return res.status(401).json({ message: 'Invalid username' }); const validPassword = await bcrypt.compare(password, user.password); if (!validPassword) return res.status(401).json({ message: 'Invalid password' }); // Generate JWT const token = jwt.sign({ id: user.id, username: user.username }, SECRET_KEY, { expiresIn: '1h' }); res.json({ token }); }); app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
  • jwt.sign(payload, secret, options) generates a token

  • expiresIn sets token expiration


3. Protect Routes with JWT

Create middleware to verify tokens:

function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // Bearer token if (!token) return res.status(401).json({ message: 'Access denied' }); jwt.verify(token, SECRET_KEY, (err, user) => { if (err) return res.status(403).json({ message: 'Invalid token' }); req.user = user; // Attach decoded user info to request next(); }); }

Protected route example:

app.get('/dashboard', authenticateToken, (req, res) => { res.send(`Hello ${req.user.username}, welcome to dashboard`); });
  • Client sends header: Authorization: Bearer

  • Middleware verifies token and allows access


4. Refresh Tokens (Optional)

  • JWTs are stateless and expire automatically

  • Use refresh tokens to generate new access tokens without re-login


5. Best Practices

  1. Never store secrets in code – use environment variables (process.env.SECRET_KEY).

  2. Use HTTPS to protect tokens in transit.

  3. Set short expiration time for access tokens and long expiration for refresh tokens.

  4. Do not store sensitive data in JWT payload.

  5. Use middleware for central token validation.


6. Example Project Structure

express-jwt/ │ ├─ routes/ │ └─ auth.js // Login route ├─ middleware/ │ └─ authMiddleware.js ├─ app.js // Express setup └─ package.json
  • auth.js → Handles login and token issuance

  • authMiddleware.js → Protects routes with JWT


JWT is a powerful method for stateless authentication and works perfectly with REST APIs built using Express.js.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes