Implementing Authentication with JWT in a Node.js App
Aug 01, 2025 am 05:59 AMJWT is a secure token format for authentication, consisting of header, payload, and signature; 2. Set up Node.js with Express, jsonwebtoken, bcryptjs, body-parser, and dotenv; 3. Create a server with user registration, password hashing, and login to generate JWT; 4. Implement token verification middleware to protect routes; 5. Store secrets in environment variables and use HTTPS in production; 6. Test registration, login, and access to protected routes using tools like curl or Postman; 7. Optionally implement refresh tokens for improved security and user experience; the system securely handles authentication using JWT in Node.js with Express and is ready for production when combined with a real database and proper security practices.
Adding authentication to a Node.js app using JSON Web Tokens (JWT) is a common and effective way to secure your APIs. Here's a practical guide to help you implement JWT-based authentication in a Node.js application using Express.

1. What is JWT?
JWT (JSON Web Token) is a compact, URL-safe token format used to securely transmit information between parties as a JSON object. It’s commonly used for authentication and authorization. A JWT typically consists of three parts: header, payload, and signature, separated by dots (e.g., xxx.yyy.zzz
).
Once a user logs in, the server generates a JWT and sends it to the client. The client then includes this token in subsequent requests (usually in the Authorization
header), and the server verifies it before granting access.

2. Setup and Dependencies
Start by initializing your Node.js project and installing required packages:
npm init -y npm install express jsonwebtoken bcryptjs body-parser dotenv npm install --save-dev nodemon
express
: Web frameworkjsonwebtoken
: To generate and verify JWTsbcryptjs
: To hash passwordsbody-parser
: To parse incoming request bodiesdotenv
: To manage environment variables
Add a script to package.json
for development:

"scripts": { "start": "node server.js", "dev": "nodemon server.js" }
3. Basic Server Setup
Create a server.js
file:
const express = require('express'); const bodyParser = require('body-parser'); const dotenv = require('dotenv'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); dotenv.config(); const app = express(); app.use(bodyParser.json()); // Simulated user database (use a real DB like MongoDB or PostgreSQL in production) const users = []; const SECRET_KEY = process.env.SECRET_KEY || 'your-super-secret-jwt-key'; // Utility: Generate JWT const generateToken = (user) => { return jwt.sign({ id: user.id, username: user.username }, SECRET_KEY, { expiresIn: '1h', }); }; // Middleware: Authenticate token const authenticateToken = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN if (!token) { return res.status(401).json({ message: 'Access denied. No token provided.' }); } jwt.verify(token, SECRET_KEY, (err, user) => { if (err) { return res.status(403).json({ message: 'Invalid or expired token.' }); } req.user = user; next(); }); };
4. User Registration
app.post('/register', async (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).json({ message: 'Username and password are required.' }); } // Check if user already exists const existingUser = users.find(u => u.username === username); if (existingUser) { return res.status(400).json({ message: 'Username already exists.' }); } // Hash password const hashedPassword = await bcrypt.hash(password, 10); const user = { id: users.length 1, username, password: hashedPassword }; users.push(user); res.status(201).json({ message: 'User registered successfully.' }); });
5. User Login and Token Generation
app.post('/login', async (req, res) => { const { username, password } = req.body; const user = users.find(u => u.username === username); if (!user) { return res.status(400).json({ message: 'Invalid credentials.' }); } const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return res.status(400).json({ message: 'Invalid credentials.' }); } const token = generateToken(user); res.json({ message: 'Login successful.', token, }); });
6. Protected Route Example
app.get('/profile', authenticateToken, (req, res) => { res.json({ message: `Welcome ${req.user.username}`, userId: req.user.id }); });
7. Environment Variables
Create a .env
file:
SECRET_KEY=change-this-to-a-very-long-random-string-in-production
This keeps your secret key secure and outside your codebase.
8. Testing the API
You can test using curl or tools like Postman:
Register:
curl -X POST http://localhost:3000/register \ -H "Content-Type: application/json" \ -d '{"username":"alice", "password":"secret123"}'
Login:
curl -X POST http://localhost:3000/login \ -H "Content-Type: application/json" \ -d '{"username":"alice", "password":"secret123"}'
Access protected route:
curl -X GET http://localhost:3000/profile \ -H "Authorization: Bearer <your-jwt-token>"
Important Security Notes
- ? Always use HTTPS in production.
- ? Store the JWT secret in environment variables — never hardcode it.
- ? Set a reasonable token expiration (e.g., 15–60 minutes). Use refresh tokens for long-lived sessions.
- ? Validate and sanitize all inputs to prevent injection attacks.
- ?? In production, use a real database with proper indexing and security.
Optional: Refresh Tokens
For better UX, implement refresh tokens to renew access tokens without requiring re-login. This adds complexity but improves security and usability.
That’s it! You now have a working JWT authentication system in Node.js. It’s minimal but covers the essentials: registration, login, token generation, verification, and protected routes.
Basically just glue the pieces together securely — and never skip hashing passwords.
The above is the detailed content of Implementing Authentication with JWT in a Node.js App. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Analysis of Secure JWT Token Generation and Verification Technology in PHP With the development of network applications, user authentication and authorization are becoming more and more important. JsonWebToken (JWT) is an open standard (RFC7519) for securely transmitting information in web applications. In PHP development, it has become a common practice to use JWT tokens for user authentication and authorization. This article will introduce secure JWT token generation and verification technology in PHP. 1. Basic knowledge of JWT in understanding how to generate and

JWT (JSONWebToken) is a lightweight authentication and authorization mechanism that uses JSON objects as security tokens to securely transmit user identity information between multiple systems. ThinkPHP6 is an efficient and flexible MVC framework based on PHP language. It provides many useful tools and functions, including JWT authentication mechanism. In this article, we will introduce how to use ThinkPHP6 for JWT authentication to ensure the security and reliability of web applications

OAuth in PHP: Creating a JWT authorization server With the rise of mobile applications and the trend of separation of front-end and back-end, OAuth has become an indispensable part of modern web applications. OAuth is an authorization protocol that protects users' resources from unauthorized access by providing standardized processes and mechanisms. In this article, we will learn how to create a JWT (JSONWebTokens) based OAuth authorization server using PHP. JWT is a type of

With the development of the Internet, more and more websites and applications need to provide API interfaces for data interaction. In this case, API authentication and encryption become very important issues. As a popular authentication and encryption mechanism, JWT and JWE are increasingly used in PHP. Well, this article will explain how to use JWT and JWE for API authentication and encryption in PHP. Basic concepts of JWT JWT stands for JSONWe

Vue.js is a popular JavaScript framework for building dynamic web applications. Implementing user login authentication is one of the necessary parts of developing web applications. This article will introduce a complete guide to implementing login verification using Vue.js, API, JWT and axios. Creating a Vue.js Application First, we need to create a new Vue.js application. We can create a Vue.js application using VueCLI or manually. Install axiosax

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

With the rapid development of the Internet and mobile Internet, more and more applications require authentication and permission control, and JWT (JSON Web Token), as a lightweight authentication and authorization mechanism, is widely used in WEB applications. Beego is an MVC framework based on the Go language, which has the advantages of efficiency, simplicity, and scalability. This article will introduce how to use JWT to implement authentication in Beego. 1. Introduction to JWT JSONWebToken (JWT) is a

First we need to import the jwt package used: io.jsonwebtokenjjwt0.8.0com.auth0java-jwt3.2.0 1. Prepare LoginUser (store login user information) and JwtUserLoginUser.javapublicclassLoginUser{privateIntegeruserId;privateStringusername;privateStringpassword;privateStringrole;generate getters and setters ...}JwtUser.javaimp
