EXPRESS JS

Create robust backend APIs with Express.js, a minimalist
framework for building server-side applications on Node.js.

Express.js Topics with Definitions and Examples

1. What is Express.js?

Definition: Express.js is a minimal and flexible Node.js web application framework.

Use: Simplifies routing, middleware handling, and HTTP requests/responses.

2. Installing Express

Install using npm:

npm install express
3. Creating First Express App

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);
4. Routing in Express

Routing defines how an application responds to client requests.

app.get('/about', (req, res) => res.send('About Page'));
5. Handling POST Request

Use express.json() middleware to parse request body.

app.use(express.json());
app.post('/submit', (req, res) => res.send(req.body));
6. Route Parameters

Capture values in the URL using : syntax.

app.get('/user/:id', (req, res) => res.send(req.params.id));
7. Query Parameters

Values sent using the URL after ?.

app.get('/search', (req, res) => res.send(req.query.q));
8. Express Middleware

Functions that execute before reaching route handlers.

app.use((req, res, next) => {
  console.log('Middleware called');
  next();
});
9. Serving Static Files

Use express.static() to serve CSS, JS, images, etc.

app.use(express.static('public'));
10. Handling 404 Errors

Catch all unmatched routes using * or middleware.

app.use((req, res) => res.status(404).send('Page Not Found'));
11. Express Router

Used to modularize routes in different files.

const router = express.Router();
router.get('/', (req, res) => res.send('Home'));
app.use('/api', router);
12. Request Object

req contains information about HTTP request.

Example: req.params, req.query, req.body

13. Response Object

res is used to send responses to the client.

Example: res.send(), res.json(), res.status()

14. JSON Response

Send JSON using res.json().

res.json({ name: 'Express', version: '1.0' });
15. Express with Template Engine

Use template engines like ejs for dynamic HTML rendering.

app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index', { title: 'Home' }));
16. Using Express Generator

express-generator is a CLI tool to scaffold a boilerplate Express app.

npm install -g express-generator
express myapp
cd myapp && npm install
17. Using CORS in Express

cors middleware allows cross-origin HTTP requests (from other domains).

const cors = require('cors');
app.use(cors());
18. Express Form Handling

To handle form data, use express.urlencoded().

app.use(express.urlencoded({ extended: true }));
app.post('/form', (req, res) => res.send(req.body));
19. Session Handling with express-session

Used to manage user sessions between requests.

const session = require('express-session');
app.use(session({ secret: 'key', resave: false, saveUninitialized: true }));
20. Cookie Handling

Use cookie-parser to parse cookies in Express.

const cookieParser = require('cookie-parser');
app.use(cookieParser());
21. File Uploads with Multer

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'));
22. Input Validation with express-validator

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');
});
23. Authentication Middleware

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'));
24. Role-Based Authorization

Control access based on user roles.

function adminOnly(req, res, next) {
  if (req.user.role === 'admin') next();
  else res.status(403).send('Forbidden');
}
25. Logging with morgan

morgan logs HTTP request details for debugging.

const morgan = require('morgan');
app.use(morgan('dev'));
26. Rate Limiting with express-rate-limit

Prevents brute-force attacks and limits requests.

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 60000, max: 10 });
app.use(limiter);
27. Using Helmet for Security

helmet sets various HTTP headers to secure Express apps.

const helmet = require('helmet');
app.use(helmet());
28. Environment Variables with dotenv

Use dotenv to load environment variables from a .env file.

require('dotenv').config();
console.log(process.env.PORT);
29. Modular Route Files

Organize routes in separate files for scalability.

const userRoutes = require('./routes/users');
app.use('/users', userRoutes);
30. Error Handling Middleware

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!');
});
31. JWT Authentication

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');
32. Protecting Routes with JWT

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');
  }
}
33. Using MongoDB with Express

Connect MongoDB to Express using mongoose or native driver.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbname');
34. MVC Architecture in Express

MVC (Model-View-Controller) separates logic: routes, business, and data.

Folder Structure: routes/, controllers/, models/

35. Deployment on Render/Heroku

Use platforms like Render, Heroku, or Railway for hosting Express apps.

// Set PORT from environment
const PORT = process.env.PORT || 3000;
app.listen(PORT);
36. Using PM2 for Production

PM2 is a process manager for Node.js apps in production.

npm install pm2 -g
pm2 start app.js
37. Clustering with Express

Use cluster module to run Express on multiple CPU cores.

const cluster = require('cluster');
if (cluster.isMaster) { cluster.fork(); } else { app.listen(3000); }
38. Using Socket.IO with Express

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'));
39. Serving JSON API

Send structured JSON data as API response.

app.get('/api', (req, res) => res.json({ id: 1, name: 'Express' }));
40. Handling Async/Await in 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); }
});
41. Connecting Express with React

Use Express as backend API and React for frontend (frontend calls backend via Axios).

42. Using Nodemailer in Express

Send emails using nodemailer inside Express route.

const transporter = nodemailer.createTransport({...});
transporter.sendMail({ to: 'x@y.com', subject: 'Test', text: 'Hello' });
43. Global Error Handling

Create a centralized middleware for all app errors.

app.use((err, req, res, next) => {
  res.status(500).json({ message: err.message });
});
44. Compression Middleware

compression reduces the size of response bodies (improves performance).

const compression = require('compression');
app.use(compression());
45. Debugging Express Apps

Use tools like console.log(), Postman, and node inspect.

Use debug package for logging modules.

46. Express.js vs Node.js

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.

47. Using Express with MySQL

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));
48. Using Sequelize ORM

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();
49. Express with PostgreSQL

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));
50. Express Unit Testing with Mocha & Chai

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));
51. Express Testing with Supertest

supertest allows HTTP assertions on Express apps.

const request = require('supertest');
request(app).get('/api').expect(200);
52. Caching in Express

Use HTTP headers or Redis to implement server-side caching in Express.

res.set('Cache-Control', 'public, max-age=600');
53. Using Redis with Express

Store session or cache data using redis.

const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value');
54. Express GraphQL API

Use express-graphql to create GraphQL APIs.

const { graphqlHTTP } = require('express-graphql');
const schema = ...;
app.use('/graphql', graphqlHTTP({ schema, graphiql: true }));
55. Creating RESTful APIs

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');
56. Status Codes in Express

Use proper status codes like 200, 201, 400, 401, 404, 500.

res.status(404).send('Not Found');
57. Using EJS with Express

ejs is a popular template engine used with Express.

app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index', { name: 'User' }));
58. Cross-Site Scripting (XSS) Protection

Use packages like xss-clean to sanitize user input.

const xss = require('xss-clean');
app.use(xss());
59. CSRF Protection in Express

Use csurf middleware to prevent CSRF attacks.

const csrf = require('csurf');
app.use(csrf());
60. Rate Limiting by IP

Restrict request frequency based on IP address to prevent abuse.

const limiter = rateLimit({ max: 100, windowMs: 15 * 60 * 1000 });
app.use(limiter);