πŸ” JSON Web Token (JWT) - Complete Guide

Understand, install, and implement JWT with Node.js and Frontend

πŸ“Œ What is JWT?

JWT (JSON Web Token) is a compact, URL-safe way of representing claims securely between two parties. It is commonly used for authentication and authorization in web applications.

It looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0IiwiaWF0IjoxNjk1NzA5ODAyfQ.mXUeFvQrPgAf0df9VNzKs_Y12nA8vn10QYFF6PvzHcQ JWT Methods

🎯 Why Use JWT?

πŸ“¦ How to Install JWT in Node.js

Install the required package:

npm install jsonwebtoken

βš™οΈ Backend Code (Node.js + Express)

Login API that issues a token

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());

const SECRET = 'your_secret_key';

// Dummy login
app.post('/login', (req, res) => {
  const { username, password } = req.body;

  if (username === 'admin' && password === '1234') {
    const token = jwt.sign({ username }, SECRET, { expiresIn: '1h' });
    res.json({ token });
  } else {
    res.status(401).json({ message: 'Invalid credentials' });
  }
});

// Middleware to protect routes
function verifyToken(req, res, next) {
  const bearer = req.headers['authorization'];
  const token = bearer && bearer.split(' ')[1];

  if (!token) return res.status(403).json({ message: 'Token required' });

  jwt.verify(token, SECRET, (err, user) => {
    if (err) return res.status(401).json({ message: 'Invalid token' });
    req.user = user;
    next();
  });
}

// Protected route
app.get('/dashboard', verifyToken, (req, res) => {
  res.send(`Hello ${req.user.username}, welcome to your dashboard`);
});

app.listen(3000, () => console.log('Server started'));

πŸ–₯️ Frontend Code (Fetch API Example)

Login and access protected data

// Login and save token
fetch('http://localhost:3000/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: 'admin', password: '1234' })
})
.then(res => res.json())
.then(data => {
  localStorage.setItem('token', data.token);
  alert('Login successful');
});

// Access dashboard
const token = localStorage.getItem('token');

fetch('http://localhost:3000/dashboard', {
  headers: {
    'Authorization': 'Bearer ' + token
  }
})
.then(res => res.text())
.then(data => console.log(data));

πŸ” Structure of a JWT

JWT has 3 parts:

You can decode JWT on jwt.io

πŸ“… When to Use JWT?

βœ… Summary