DEV Community

Cover image for Understanding JWT in Node.js: A Guide with Pros, Cons, and Code Examples
Abdelhakim mohamed
Abdelhakim mohamed

Posted on

2 1 1 1

Understanding JWT in Node.js: A Guide with Pros, Cons, and Code Examples

What is JWT?

  • JWT (JSON Web Token) is a compact token used for secure info exchange.
  • Contains 3 parts:
    1. Header: Type & signing algorithm.
    2. Payload: Claims (user data).
    3. Signature: Validates integrity.

Image description


JWT Example in Node.js

Setup Node.js Project

npm init -y
npm install express jsonwebtoken bcryptjs
Enter fullscreen mode Exit fullscreen mode

Code: Simple Login & Token Creation

const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const app = express();
app.use(express.json());

const users = [];
const JWT_SECRET = 'your-secret-key'; // this should be stored inside the env file

app.post('/signup', async (req, res) => {
  const { username, password } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);
  users.push({ username, password: hashedPassword });
  res.status(201).send('User registered');
});

app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username);
  if (!user || !(await bcrypt.compare(password, user.password))) {
    return res.status(401).send('Invalid credentials');
  }
  const token = jwt.sign({ username }, JWT_SECRET, { expiresIn: '1h' });
  res.json({ token });
});
Enter fullscreen mode Exit fullscreen mode

Code: Protecting Routes with JWT Middleware

const authenticateToken = (req, res, next) => {
  const token = req.headers['authorization'];
  if (!token) return res.status(403).send('Token required');
  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) return res.status(403).send('Invalid token');
    req.user = user;
    next();
  });
};

app.get('/dashboard', authenticateToken, (req, res) => {
  res.send(`Hello ${req.user.username}`);
});
Enter fullscreen mode Exit fullscreen mode

Pros & Cons of JWT

Pros:

  • Stateless: No session storage.
  • Compact: Easy to transmit.
  • Cross-domain: Securely works across systems.

Cons:

  • Token size: Large tokens can affect performance.
  • Cannot revoke: Once issued, difficult to invalidate some bypass this issue by using refresh tokens.
  • Data exposure: Payload is not encrypted (avoid sensitive info).

Conclusion

JWT makes authentication simple and scalable, but be aware of its security implications. Keep tokens secure with short expiration times and HTTPS.


References

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
khaled_sedik profile image
Khaled Sdek

Thank you for the info

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay