Create robust backend APIs with Express.js, a minimalist
framework for building server-side applications on Node.js.
Definition: Express.js is a minimal and flexible Node.js web application framework.
Use: Simplifies routing, middleware handling, and HTTP requests/responses.
Install using npm:
npm install express
Example of a basic server using Express:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello Express'));
app.listen(3000);
Routing defines how an application responds to client requests.
app.get('/about', (req, res) => res.send('About Page'));
Use express.json()
middleware to parse request body.
app.use(express.json());
app.post('/submit', (req, res) => res.send(req.body));
Capture values in the URL using :
syntax.
app.get('/user/:id', (req, res) => res.send(req.params.id));
Values sent using the URL after ?
.
app.get('/search', (req, res) => res.send(req.query.q));
Functions that execute before reaching route handlers.
app.use((req, res, next) => {
console.log('Middleware called');
next();
});
Use express.static()
to serve CSS, JS, images, etc.
app.use(express.static('public'));
Catch all unmatched routes using *
or middleware.
app.use((req, res) => res.status(404).send('Page Not Found'));
Used to modularize routes in different files.
const router = express.Router();
router.get('/', (req, res) => res.send('Home'));
app.use('/api', router);
req
contains information about HTTP request.
Example: req.params
, req.query
,
req.body
res
is used to send responses to the client.
Example: res.send()
, res.json()
,
res.status()
Send JSON using res.json()
.
res.json({ name: 'Express', version: '1.0' });
Use template engines like ejs
for dynamic HTML rendering.
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index', { title: 'Home'
}));
express-generator
is a CLI tool to scaffold a boilerplate
Express app.
npm install -g express-generator
express myapp
cd myapp && npm install
cors
middleware allows cross-origin HTTP requests (from
other domains).
const cors = require('cors');
app.use(cors());
To handle form data, use express.urlencoded()
.
app.use(express.urlencoded({ extended: true }));
app.post('/form', (req, res) => res.send(req.body));
Used to manage user sessions between requests.
const session = require('express-session');
app.use(session({ secret: 'key', resave: false, saveUninitialized:
true }));
Use cookie-parser
to parse cookies in Express.
const cookieParser = require('cookie-parser');
app.use(cookieParser());
Multer middleware is used to handle file uploads.
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('myFile'), (req, res) =>
res.send('Uploaded'));
Used to validate and sanitize user inputs.
const { body, validationResult } = require('express-validator');
app.post('/user', body('email').isEmail(), (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({
errors: errors.array() });
res.send('Valid');
});
Custom middleware to restrict access to authenticated users only.
function auth(req, res, next) {
if (req.session.user) next();
else res.redirect('/login');
}
app.get('/dashboard', auth, (req, res) => res.send('Welcome'));
Control access based on user roles.
function adminOnly(req, res, next) {
if (req.user.role === 'admin') next();
else res.status(403).send('Forbidden');
}
morgan
logs HTTP request details for debugging.
const morgan = require('morgan');
app.use(morgan('dev'));
Prevents brute-force attacks and limits requests.
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 60000, max: 10 });
app.use(limiter);
helmet
sets various HTTP headers to secure Express apps.
const helmet = require('helmet');
app.use(helmet());
Use dotenv
to load environment variables from a .env
file.
require('dotenv').config();
console.log(process.env.PORT);
Organize routes in separate files for scalability.
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);
Centralized error handling in Express with 4-parameter middleware.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
JWT (JSON Web Token) is used for stateless authentication in Express.
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, 'secret');
const data = jwt.verify(token, 'secret');
Use a middleware to verify tokens before allowing access.
function auth(req, res, next) {
const token = req.headers.authorization;
try {
jwt.verify(token, 'secret');
next();
} catch {
res.status(401).send('Unauthorized');
}
}
Connect MongoDB to Express using mongoose
or native
driver.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbname');
MVC (Model-View-Controller) separates logic: routes, business, and data.
Folder Structure: routes/
, controllers/
,
models/
Use platforms like Render, Heroku, or Railway for hosting Express apps.
// Set PORT from environment
const PORT = process.env.PORT || 3000;
app.listen(PORT);
PM2 is a process manager for Node.js apps in production.
npm install pm2 -g
pm2 start app.js
Use cluster
module to run Express on multiple CPU cores.
const cluster = require('cluster');
if (cluster.isMaster) { cluster.fork(); } else { app.listen(3000); }
socket.io
enables real-time bi-directional communication.
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', socket => console.log('User connected'));
Send structured JSON data as API response.
app.get('/api', (req, res) => res.json({ id: 1, name: 'Express'
}));
Use try-catch blocks to safely handle errors in async functions.
app.get('/', async (req, res) => {
try { const data = await getData(); res.send(data); }
catch (err) { res.status(500).send(err.message); }
});
Use Express as backend API and React for frontend (frontend calls backend via Axios).
Send emails using nodemailer
inside Express route.
const transporter = nodemailer.createTransport({...});
transporter.sendMail({ to: 'x@y.com', subject: 'Test', text: 'Hello'
});
Create a centralized middleware for all app errors.
app.use((err, req, res, next) => {
res.status(500).json({ message: err.message });
});
compression
reduces the size of response bodies (improves
performance).
const compression = require('compression');
app.use(compression());
Use tools like console.log()
, Postman
, and
node inspect
.
Use debug
package for logging modules.
Node.js is the platform, Express.js is a web framework built on top of Node.js.
Express simplifies handling routes, middleware, and requests/responses.
Use mysql2
or sequelize
for connecting MySQL
with Express.
const mysql = require('mysql2');
const db = mysql.createConnection({host: 'localhost', user: 'root',
database: 'test'});
db.query('SELECT * FROM users', (err, results) =>
console.log(results));
Sequelize is a promise-based ORM for Node.js (supports MySQL, PostgreSQL, etc.).
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('test', 'root', '', { dialect:
'mysql' });
const User = sequelize.define('User', { name: DataTypes.STRING
});
sequelize.sync();
Use pg
module to integrate PostgreSQL database in
Express.
const { Client } = require('pg');
const client = new Client();
client.connect();
client.query('SELECT * FROM table', (err, res) =>
console.log(res.rows));
Test routes and logic using mocha
and chai
.
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
chai.request(app).get('/').end((err, res) =>
res.should.have.status(200));
supertest
allows HTTP assertions on Express apps.
const request = require('supertest');
request(app).get('/api').expect(200);
Use HTTP headers or Redis to implement server-side caching in Express.
res.set('Cache-Control', 'public, max-age=600');
Store session or cache data using redis
.
const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value');
Use express-graphql
to create GraphQL APIs.
const { graphqlHTTP } = require('express-graphql');
const schema = ...;
app.use('/graphql', graphqlHTTP({ schema, graphiql: true }));
Use CRUD routes (GET, POST, PUT, DELETE) to create RESTful services.
app.get('/users');
app.post('/users');
app.put('/users/:id');
app.delete('/users/:id');
Use proper status codes like 200, 201, 400, 401, 404, 500.
res.status(404).send('Not Found');
ejs
is a popular template engine used with Express.
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index', { name: 'User'
}));
Use packages like xss-clean
to sanitize user input.
const xss = require('xss-clean');
app.use(xss());
Use csurf
middleware to prevent CSRF attacks.
const csrf = require('csurf');
app.use(csrf());
Restrict request frequency based on IP address to prevent abuse.
const limiter = rateLimit({ max: 100, windowMs: 15 * 60 * 1000
});
app.use(limiter);