0
0
ExpressHow-ToBeginner · 4 min read

How to Generate JWT Token in Express: Simple Guide

To generate a JWT token in Express, use the jsonwebtoken package's sign() method by passing a payload, a secret key, and optional options like expiration. This creates a secure token string you can send to clients for authentication.
📐

Syntax

The jsonwebtoken package provides the sign() method to create a JWT token.

  • payload: Data you want to include in the token, usually user info.
  • secretOrPrivateKey: A secret string to sign the token securely.
  • options: Optional settings like token expiration time.
javascript
jwt.sign(payload, secretOrPrivateKey, [options])
💻

Example

This example shows how to generate a JWT token in an Express route after a user logs in. It uses jsonwebtoken to create a token with a user ID and an expiration time of 1 hour.

javascript
import express from 'express';
import jwt from 'jsonwebtoken';

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

const SECRET_KEY = 'your_secret_key_here';

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

  // Dummy user check (replace with real authentication)
  if (username === 'user' && password === 'pass') {
    const payload = { username };
    const token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1h' });
    res.json({ token });
  } else {
    res.status(401).json({ message: 'Invalid credentials' });
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
{"token":"<JWT token string>"}
⚠️

Common Pitfalls

Common mistakes when generating JWT tokens include:

  • Using a weak or hardcoded secret key that is easy to guess.
  • Not setting an expiration time, which can cause tokens to be valid forever.
  • Including sensitive information in the payload that should not be exposed.
  • Forgetting to handle errors from jwt.sign().
javascript
/* Wrong: No expiration and weak secret */
const tokenWrong = jwt.sign({ user: 'user' }, '123');

/* Right: Strong secret and expiration */
const tokenRight = jwt.sign({ user: 'user' }, process.env.SECRET_KEY, { expiresIn: '1h' });
📊

Quick Reference

Remember these tips when generating JWT tokens in Express:

  • Always use a strong, secret key stored securely (e.g., environment variables).
  • Set a reasonable expiration time with expiresIn.
  • Keep the payload minimal and avoid sensitive data.
  • Use jsonwebtoken package for easy token creation.

Key Takeaways

Use the jsonwebtoken package's sign() method to generate JWT tokens in Express.
Always protect your secret key and never hardcode it in your code.
Set token expiration to limit how long tokens are valid.
Keep the token payload small and avoid sensitive information.
Handle errors properly when creating tokens.