JWT Authentication

  • JWT authentication secures applications by using JSON Web Tokens to verify users and protect Node.js APIs.

  • JSON Web Token (JWT)

    A JSON Web Token (JWT) is a compact, URL-safe token used to securely transmit information between a client and a server. The information inside a JWT is digitally signed, making it tamper-proof.

    Install Required Packages

npm install jsonwebtoken
  • Login API – Generate JWT

JWT Authentication in Express.js

This code demonstrates JWT-based authentication in Express.js. After login, the server generates a signed JWT, which the client sends with each request. Middleware verifies the token to protect routes like /profile, ensuring secure, stateless access control.

const jwt = require("jsonwebtoken");

const SECRET_KEY = "jwtSecretKey";

app.post("/login", (req, res) => {
  const { email, password } = req.body;

  if (email === "user@gmail.com" && password === "1234") {
    const token = jwt.sign(
      { email },
      SECRET_KEY,
      { expiresIn: "1h" }
    );

    res.json({ token });
  } else {
    res.status(401).send("Invalid credentials");
  }
});
  • Middleware – Verify JWT

function authenticateToken(req, res, next) {
  const token = req.headers["authorization"];

  if (!token) {
    return res.status(403).send("Token required");
  }

  jwt.verify(token, SECRET_KEY, (err, user) => {
    if (err) {
      return res.status(401).send("Invalid token");
    }

    req.user = user;
    next();
  });
}
  • Protected Route Using JWT

app.get("/profile", authenticateToken, (req, res) => {
  res.send("Welcome " + req.user.email);
});
Lesson image