>_
EngineeringNotes
← Back to Node.js & Runtimes
Module 06

Express.js (Real Backend)

The minimal and flexible Node.js web framework designed for high-performance application development and API creation.

01

What is Express.js?

Definition: Express.js is a minimal and flexible Node.js web framework used to build web applications and APIs. It simplifies everything you did manually with the native HTTP module.

Key Engineering Concept

Express is a thin layer built on top of Node's HTTP module that simplifies routing, middleware, and request handling.

  • Abstraction over low-level server logic.
  • Modular architecture via Middleware.
02

Why Express.js? (Manual vs Framework)

FeatureNative HTTP ModuleExpress.js
RoutingManual (if/else chains)Clean & Declarative Routes
Body ParsingManual Stream HandlingBuilt-in JSON Parser
MiddlewareNot Supported nativelyFirst-class Support
03

Setting Up Express

npm install express
app.js
javascript
import express from 'express';

const app = express();

app.listen(3000, () => {
    console.log("Server running on port 3000");
});
04

Routing in Express

Express supports all standard HTTP methods: GET, POST, PUT, DELETE.

routes.js
javascript
app.get('/', (req, res) => {
    res.send("Home Page");
});

app.get('/about', (req, res) => {
    res.send("About Page");
});
05

The Request Object (req)

The request object contains information about the HTTP request that raised the event.

req.params

URL segment parameters (e.g. /user/:id)

req.query

Query string parameters (e.g. ?id=1)

req.body

Incoming request payload

req.headers

Request headers

dynamic-routes.js
javascript
app.get('/user/:id', (req, res) => {
    console.log(req.params.id);
    res.send("User ID received");
});
06

The Response Object (res)

MethodPrimary Use Case
res.send()Send generic data payloads (string, buffer, object)
res.json()Strictly transmit JSON responses
res.status()Manually set HTTP status codes
javascript
javascript
res.status(201).json({ message: "Resource created successfully" });
07

Middleware: The Lifeblood of Express

Definition:Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.

!

Critical Rule: Always call next() within your middleware or the request will hang indefinitely.

global-middleware.js
javascript
app.use((req, res, next) => {
    console.log("Timestamp:", Date.now());
    next(); // Pass control to the next handler
});

Built-in Middleware

Express provides built-in functions for common needs, most importantly parsing JSON.

javascript
javascript
app.use(express.json());

Without this, req.body will return undefined.

Route-Level Middleware

Execute logic only for specific endpoints (e.g. Authentication, Validation).

javascript
javascript
const auth = (req, res, next) => {
    // check token...
    next();
};

app.get('/dashboard', auth, (req, res) => {
    res.send("Dashboard");
});
08

Handling POST Payloads

Handling incoming data requires the JSON middleware to process the request body stream into a usable object.

post-handler.js
javascript
app.use(express.json());

app.post('/data', (req, res) => {
    console.log(req.body); // { name: "Shivam" }
    res.send("Data received");
});
09

Error Handling Middleware

A specialized middleware designed to catch all errors passed via next(err).

Requirement: Error-handling middleware must always have exactly 4 parameters.

error-handler.js
javascript
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send("Something went wrong!");
});
10

Express Router (Modular Architecture)

As applications scale, splitting routes into separate files becomes necessary for maintainability.

user-router.js
javascript
// routes/user.js
const router = express.Router();

router.get('/', (req, res) => {
    res.send("User List");
});

export default router;
main-app.js
javascript
// app.js
import userRoutes from './routes/user.js';

app.use('/users', userRoutes);
11

Serving Static Files & Status Codes

Serving Static Assets

Directly serve images, CSS, or frontend builds from a directory.

javascript
javascript
app.use(express.static('public'));

Files in /public are now accessible via root URL (e.g. /favicon.ico).

Consistent Status Codes

200

OK

201

Created

404

Not Found

500

Server Error

12

Interview Assessment Preparation

What is Express.js?
Answer:A minimal and flexible Node.js web framework designed for building scalable APIs and web applications.
What is middleware in Express?
Answer:A function that has access to the request object, response object, and the next function, allowing it to modify data or terminate the request-response cycle.
Why is express.json() middleware necessary?
Answer:To parse incoming JSON request bodies, which are otherwise received as raw buffers that Node doesn't parse automatically.
Explain the difference between req.params and req.query.
Answer:req.params refers to variables defined in the URL path (e.g. /user/:id), while req.query refers to key-value pairs in the query string (e.g. /search?q=nodejs).
What is the role of next() in Express?
Answer:It is a function that, when called, passes control to the next middleware or route handler in the sequence.
How is modular routing achieved in Express?
Answer:Through the Express Router (express.Router()), which allows grouping related routes into separate files for better organization.

The Express Request Pipeline

Client Request
Middleware Chain
Route Handler (Business Logic)
Final Response