Implement JWT Authentication in Node.js and Express

Use this AI prompt to generate complete JWT authentication for Node.js with login, signup, and middleware-based token verification for protected routes.

🧠 What This Prompt Does

This AI prompt helps you create a JWT-based authentication system for Node.js using Express.
It includes signup/login endpoints, token generation, and middleware for route protection.


💬 The Prompt

You are a backend developer.
Generate a JWT authentication system in Node.js using Express.

Requirements:

- Signup and login routes
- Generate JWT tokens using jsonwebtoken
- Middleware to verify tokens
- Return proper error codes for unauthorized requests

🚀 Example Output (AI Generated)

import express from 'express';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';

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

const users = [];
const SECRET = 'mysecretkey';

// Signup route
app.post('/signup', async (req, res) => {
  const { email, password } = req.body;
  const hash = await bcrypt.hash(password, 10);
  users.push({ email, password: hash });
  res.status(201).json({ message: 'User created' });
});

// Login route
app.post('/login', async (req, res) => {
  const { email, password } = req.body;
  const user = users.find((u) => u.email === email);
  if (!user || !(await bcrypt.compare(password, user.password))) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }
  const token = jwt.sign({ email }, SECRET, { expiresIn: '1h' });
  res.json({ token });
});

// Auth middleware
const verifyToken = (req, res, next) => {
  const auth = req.headers.authorization;
  if (!auth) return res.status(401).json({ error: 'No token provided' });
  try {
    req.user = jwt.verify(auth.split(' ')[1], SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
};

// Protected route
app.get('/profile', verifyToken, (req, res) => {
  res.json({ email: req.user.email });
});

📘 When to Use This Prompt

  • When building secure login flows in Node.js.
  • For APIs requiring authenticated user access.
  • When replacing session-based authentication with tokens.

💡 Best Practices

  • Store tokens securely (prefer httpOnly cookies).
  • Use refresh tokens for long-lived sessions.
  • Always validate token expiry on the backend.
  • Rotate JWT secrets periodically for added security.

🏁 Summary

This prompt generates a complete JWT authentication setup for Express, helping you secure your backend APIs efficiently and cleanly.

Frequently Asked Questions

What is JWT used for?

JSON Web Tokens (JWTs) securely transmit user authentication data between the client and server.

Where should I store the JWT on the client?

Use httpOnly cookies or localStorage depending on your app’s security needs. httpOnly cookies are safer for most apps.

How long should JWTs be valid for?

Short-lived (15–60 min) access tokens combined with refresh tokens are best practice.

nodejsexpressauthjwtmiddlewareai-prompt

Advertisement