🧠 Understanding Express.js Middleware & Common Middleware Functions

Middleware functions are the backbone of request handling in Express.js. They allow you to intercept and manipulate requests and responses at various points in the request-response cycle.
🔧 What is Middleware in Express?
Middleware in Express.js is a function that has access to the request (req)
, response (res)
, and the next()
function. It can perform a variety of tasks, such as executing code, modifying request/response objects, ending the cycle, or passing control to the next function in the stack.
✅ Middleware Functions Can:
a. Execute any code
b. Make changes to the request and response objects
c. End the request-response cycle
d. Call the next middleware in the stack using
next()
🚀 Commonly Used Middleware
1. express.json()
– Handling JSON Requests
express.json()
is a built-in middleware function in Express used to parse incoming requests with JSON payloads. This is especially useful when you're dealing with POST
or PUT
requests where data is sent in the body.
🧪 Example: Using express.json()
for a /sum
endpoint
const express = require('express');
const app = express();
// Middleware to parse JSON body
app.use(express.json());
app.post('/sum', function (req, res) {
console.log(req.body); // logs: { a: 5, b: 7 }
const a = parseInt(req.body.a);
const b = parseInt(req.body.b);
res.json({
ans: a + b
});
});
app.listen(3001, () => {
console.log("Server is running on port 3001");
});
🧠 Why it's useful:
Without express.json()
, req.body
would be undefined
for JSON payloads. This middleware ensures you can access and process the data easily.
2. cors
– Cross-Origin Resource Sharing
CORS is a security feature in browsers that restricts web pages from making requests to a different domain than the one that served the web page. If you're developing an API that's consumed by frontends hosted on different origins, enabling CORS is a must.
🔧 Install cors
npm install cors
⚙️ Example: Using cors
in Express
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
app.get('/data', (req, res) => {
res.json({ message: 'CORS is enabled!' });
});
app.listen(3002, () => {
console.log("CORS-enabled server running on port 3002");
});
🛡️ Why it's important:
If a browser blocks a cross-origin request due to CORS, your frontend app won’t be able to access the backend. By using the cors
middleware, you can allow or restrict which origins are permitted to communicate with your API.
Subscribe to my newsletter
Read articles from Samyog Ghimire directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
