Learn how to design, build, and deploy a production-ready REST API with authentication, validation, and error handling.
Initialise a new Node.js project with npm init -y and install Express: npm install express. Create an index.js entry point and spin up a basic server on port 3000.
const express = require('express')
const app = express()
app.use(express.json())
app.get('/', (req, res) => {
res.json({ message: 'API is running' })
})
app.listen(3000, () => console.log('Server on port 3000'))Organise routes into separate files. Use Express Router to group related endpoints. Controllers handle business logic, keeping routes thin and readable.
Keep controllers thin — move complex logic into service files. This makes testing and maintenance much easier long-term.
const router = require('express').Router()
const { getUsers, createUser } = require('../controllers/users')
router.get('/', getUsers)
router.post('/', createUser)
module.exports = routerInstall jsonwebtoken and bcryptjs. Hash passwords before storing, sign a token on login, and verify it in middleware before protected routes.
Never store plain-text passwords. Always use bcrypt with a salt rounds value of at least 10.
const jwt = require('jsonwebtoken')
module.exports = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1]
if (!token) return res.status(401).json({ error: 'Unauthorized' })
try {
req.user = jwt.verify(token, process.env.JWT_SECRET)
next()
} catch {
res.status(401).json({ error: 'Invalid token' })
}
}Use express-validator to validate request bodies. Build a centralised error handler middleware that formats all errors consistently so clients always receive a predictable shape.
Place your global error handler after all route definitions. Express identifies it by the 4-argument signature (err, req, res, next).
This tutorial covers Node.js 20+. If you are on an older version, some syntax may differ slightly.
Backend engineer and open-source contributor.
Join 15,000+ Indian developers and creators receiving our curated newsletter every Sunday morning.
No spam. Only high-quality content. Unsubscribe anytime.