Introduction
Security is essential when building backend APIs. One of the simplest and fastest ways to protect your endpoints is through Basic Authentication.
In this beginner-friendly tutorial, you'll learn how to:
- Set up a basic Express.js server
- Create protected routes
- Use HTTP Basic Auth middleware to restrict access
This method is ideal for internal tools, admin panels, or early-stage projects that don't require full OAuth or JWT setups yet.
🛠️ What You’ll Need
- Node.js installed on your system
- Basic knowledge of JavaScript
- A tool like Postman or curl for testing
Let’s dive in step-by-step 👇
🔧 Step 1: Create a New Project
Start by setting up a new Node.js project:
mkdir express-auth-api
cd express-auth-api
npm init -y
Install Express:
npm install express
📄 Step 2: Create the Entry File
Let’s create a file called index.js
and set up a simple Express server.
// index.js
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.send('Welcome to the public API!');
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Now start your server:
node index.js
Visit http://localhost:3000/
— it should return a welcome message.
🔐 Step 3: Create Basic Auth Middleware
We’ll write a custom middleware to check for a valid username and password in the request headers.
// auth.js
const basicAuth = (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader) {
res.setHeader('WWW-Authenticate', 'Basic');
return res.status(401).send('Authentication required.');
}
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
// Simple hardcoded credentials
const validUsername = 'admin';
const validPassword = 'password123';
if (username === validUsername && password === validPassword) {
next();
} else {
return res.status(403).send('Access denied.');
}
};
module.exports = basicAuth;
📘 How it works:
- Checks for
Authorization
header - Decodes the base64 credentials
- Compares with hardcoded values
- Grants or denies access
🔐 Step 4: Protect a Route Using Middleware
Now import the middleware into index.js
and apply it to any route you want to secure.
// index.js (continued)
const basicAuth = require('./auth');
app.get('/protected', basicAuth, (req, res) => {
res.send('This is a protected route. Welcome, admin!');
});
Restart your server and try accessing:
http://localhost:3000/
→ Works without authhttp://localhost:3000/protected
→ Prompts for username/password
🧪 Step 5: Test in Postman or curl
Using curl:
curl -u admin:password123 http://localhost:3000/protected
Using Postman:
- Go to the Authorization tab
- Set type to Basic Auth
- Enter:
- Username:
admin
- Password:
password123
- Username:
- Send request to
/protected
You should see:This is a protected route. Welcome, admin!
🔒 Best Practices
- ✅ Never hardcode passwords in production — use environment variables
- ✅ Use HTTPS to prevent credentials from being exposed
- ✅ For real apps, upgrade to JWT, OAuth, or session-based authentication
🌐 SEO/DevOps Tie-In
Even for internal APIs or admin panels, securing endpoints prevents unauthorized access, which helps protect your SEO tools, analytics data, and backend infrastructure. A secure backend is a healthy backend.
🎯 Conclusion
You've just added Basic Authentication to an Express API — a quick and easy way to lock down endpoints during development or internal testing.
Next, try expanding this by:
- Using hashed passwords (with bcrypt)
- Protecting multiple routes
- Connecting it to a login system
For more tutorials like this, explore our Backend & APIs section!
0 Comments