Hey little coder! ๐
Ever wondered how websites like Facebook know who you are? Or how some users can access admin stuff, and others can’t?
Thatโs where Authentication and Authorization come in.
Letโs break them down and build a secure Node.js app together ๐
๐ง What is Authentication vs Authorization?
๐ค Authentication = “Who are you?”
You log in with your email and password. The system checks if you’re really you.
Like a security guard checking your ID ๐ชช
๐ Authorization = “What can you do?”
Once you’re in, what are you allowed to do? View pages? Edit users? Access admin panel?
Like getting a wristband at a concert ๐๏ธ โ red for VIP, blue for regular.
๐ง Tools Weโll Use
| Tool | Purpose |
|---|---|
bcryptjs | Hash passwords |
jsonwebtoken | Create and verify JWTs |
express | Create server and APIs |
middleware | Secure routes and check permissions |
๐ ๏ธ Step-by-Step: Secure a Node.js App (With JWT + bcrypt)
We’ll build a simple system:
- Register new users
- Login users with JWT
- Protect private routes
- Restrict access by role (admin vs user)
โ๏ธ 1. Set Up Your Project
bashCopyEditmkdir auth-app
cd auth-app
npm init -y
npm install express bcryptjs jsonwebtoken dotenv
Folder Structure (Simple Version):
bashCopyEditauth-app/
โโโ index.js
โโโ .env
โโโ users.js
โโโ middleware/
โโโ auth.js
๐ 2. Create a Simple User Store (Without DB For Now)
jsCopyEdit// users.js
const users = [];
module.exports = users;
Weโll simulate a database with an array for now ๐ฆ
๐ 3. Register a New User
โ Steps:
- Hash the password with
bcryptjs - Save the user to our store
jsCopyEdit// index.js
const express = require('express');
const bcrypt = require('bcryptjs');
const users = require('./users');
const app = express();
app.use(express.json());
app.post('/register', async (req, res) => {
const { email, password, role } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ email, password: hashedPassword, role: role || "user" });
res.status(201).json({ message: "โ
User registered!" });
});
๐ 4. User Login and JWT Token Creation
jsCopyEditconst jwt = require('jsonwebtoken');
require('dotenv').config();
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = users.find(u => u.email === email);
if (!user) return res.status(400).json({ message: "User not found" });
const valid = await bcrypt.compare(password, user.password);
if (!valid) return res.status(401).json({ message: "Invalid credentials" });
const token = jwt.sign({ email: user.email, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
});
๐๏ธ
.envfile should contain:
iniCopyEditJWT_SECRET=supersecretkey
๐ 5. Middleware to Protect Routes
jsCopyEdit// middleware/auth.js
const jwt = require('jsonwebtoken');
function authMiddleware(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader?.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
module.exports = authMiddleware;
๐ช 6. Create a Protected Route
jsCopyEditconst auth = require('./middleware/auth');
app.get('/profile', auth, (req, res) => {
res.json({ message: `Welcome ${req.user.email}!`, role: req.user.role });
});
๐งช Send a request with the token in header:
makefileCopyEditAuthorization: Bearer <token>
๐งโโ๏ธ 7. Role-Based Access Control
Letโs only allow admins to access certain routes:
jsCopyEditfunction adminOnly(req, res, next) {
if (req.user.role !== 'admin') return res.sendStatus(403);
next();
}
app.get('/admin', auth, adminOnly, (req, res) => {
res.json({ message: "Welcome Admin! ๐" });
});
๐ This checks the user’s role from the JWT payload.
๐จ Infographic Placeholder
Title: JWT Authentication Flow (Visual)

๐ Recap โ What We Learned
โ
What authentication and authorization mean
โ
How to hash passwords with bcrypt
โ
How JWT helps us create secure sessions
โ
Middleware to protect routes
โ
Role-based access to limit actions
๐ฌ Real-World Tips
- ๐งฏ Always store passwords hashed (never plain!)
- ๐ก๏ธ Keep your
JWT_SECRETsafe and private - โป๏ธ Use token expiration to force re-login after some time
- ๐ซ Never expose sensitive info inside JWT
๐ Ready to Build Real Projects?
Try building a:
- ๐งโ๐ Student dashboard with roles: admin, teacher, student
- ๐ E-commerce site with buyer and seller dashboards
- โ๏ธ Blog with author/editor permissions
๐งฉ Coming Up in Part 2?
If you’d like, I can show:
- How to store users in MongoDB or PostgreSQL
- Use refresh tokens for longer sessions
- Logout and token invalidation
๐งก Support & Learn With Us
If you learned something today, help us grow:
๐บ Subscribe to Web Codder on YouTube
๐ธ Follow us on Instagram
๐ฌ Join our WhatsApp community
Letโs make the web safer, together ๐ช๐
