Express.js (Real Backend)
The minimal and flexible Node.js web framework designed for high-performance application development and API creation.
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.
Why Express.js? (Manual vs Framework)
| Feature | Native HTTP Module | Express.js |
|---|---|---|
| Routing | Manual (if/else chains) | Clean & Declarative Routes |
| Body Parsing | Manual Stream Handling | Built-in JSON Parser |
| Middleware | Not Supported natively | First-class Support |
Setting Up Express
npm install expressimport express from 'express';
const app = express();
app.listen(3000, () => {
console.log("Server running on port 3000");
});Routing in Express
Express supports all standard HTTP methods: GET, POST, PUT, DELETE.
app.get('/', (req, res) => {
res.send("Home Page");
});
app.get('/about', (req, res) => {
res.send("About Page");
});The Request Object (req)
The request object contains information about the HTTP request that raised the event.
req.paramsURL segment parameters (e.g. /user/:id)
req.queryQuery string parameters (e.g. ?id=1)
req.bodyIncoming request payload
req.headersRequest headers
app.get('/user/:id', (req, res) => {
console.log(req.params.id);
res.send("User ID received");
});The Response Object (res)
| Method | Primary Use Case |
|---|---|
| res.send() | Send generic data payloads (string, buffer, object) |
| res.json() | Strictly transmit JSON responses |
| res.status() | Manually set HTTP status codes |
res.status(201).json({ message: "Resource created successfully" });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.
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.
app.use(express.json());Without this, req.body will return undefined.
Route-Level Middleware
Execute logic only for specific endpoints (e.g. Authentication, Validation).
const auth = (req, res, next) => {
// check token...
next();
};
app.get('/dashboard', auth, (req, res) => {
res.send("Dashboard");
});Handling POST Payloads
Handling incoming data requires the JSON middleware to process the request body stream into a usable object.
app.use(express.json());
app.post('/data', (req, res) => {
console.log(req.body); // { name: "Shivam" }
res.send("Data received");
});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.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something went wrong!");
});Express Router (Modular Architecture)
As applications scale, splitting routes into separate files becomes necessary for maintainability.
// routes/user.js
const router = express.Router();
router.get('/', (req, res) => {
res.send("User List");
});
export default router;// app.js
import userRoutes from './routes/user.js';
app.use('/users', userRoutes);Serving Static Files & Status Codes
Serving Static Assets
Directly serve images, CSS, or frontend builds from a directory.
app.use(express.static('public'));Files in /public are now accessible via root URL (e.g. /favicon.ico).
Consistent Status Codes
OK
Created
Not Found
Server Error