Loading

Quipoin Menu

Learn • Practice • Grow

express-js / Custom Middleware & Third-party (body-parser cors)
tutorial

Custom Middleware & Third-party (body-parser cors)

While Express provides some built-in middleware, real-world applications often need custom logic or additional features. This is where custom middleware and third-party middleware come in. Think of them as tools you build yourself or borrow from others to solve specific problems.

Creating Custom Middleware

Custom middleware is just a function that takes (req, res, next) parameters. You can create middleware for logging, authentication, validation, or any custom logic.

Example 1: Logger Middleware
// Custom logger middleware
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
next(); // Don't forget to call next!
};

app.use(logger); // Use it for all routes

Example 2: Authentication Middleware
// Check if user is authenticated
const checkAuth = (req, res, next) => {
if (req.headers.authorization) {
// User is authenticated, proceed
next();
} else {
// User not authenticated, send error
res.status(401).send('Unauthorized');
}
};

// Apply only to routes that need authentication
app.get('/dashboard', checkAuth, (req, res) => {
res.send('Welcome to your dashboard');
});

Example 3: Middleware with Parameters

Sometimes you need to pass parameters to middleware. You can create a function that returns the middleware:
const requireRole = (role) => {
return (req, res, next) => {
if (req.user && req.user.role === role) {
next();
} else {
res.status(403).send('Forbidden');
}
};
};

app.get('/admin', requireRole('admin'), (req, res) => {
res.send('Admin panel');
});

Third-party Middleware

The Express ecosystem has thousands of third-party middleware packages that you can install via npm. Let's look at two popular ones: body-parser and cors.

Body-parser

Before Express 4.16, body-parser was a separate package. Now its functionality is built into Express (express.json and express.urlencoded), but you might still see it in older codebases. It parses incoming request bodies.
// Install: npm install body-parser

const bodyParser = require('body-parser');

// Parse JSON bodies
app.use(bodyParser.json());

// Parse URL-encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));

CORS (Cross-Origin Resource Sharing)

CORS is a security feature that controls which domains can access your API. When building APIs for frontend applications, you'll almost always need to enable CORS.
// Install: npm install cors

const cors = require('cors');

// Enable CORS for all routes
app.use(cors());

// Or with specific options
app.use(cors({
origin: 'https://myfrontend.com',
optionsSuccessStatus: 200
}));

Without CORS, your frontend (running on a different domain/port) won't be able to access your API.

Other Popular Third-party Middleware
  • morgan: HTTP request logger
  • helmet: Helps secure your app by setting various HTTP headers
  • compression: Gzip compression for responses
  • express-session: Session management
  • cookie-parser: Parse cookie headers

Two Minute Drill
  • Custom middleware are simple functions with (req, res, next) signature.
  • Always call next() or send a response to avoid hanging requests.
  • Third-party middleware extends Express functionality.
  • cors is essential for APIs accessed by frontend apps.
  • body-parser is largely replaced by built-in methods but still found in legacy code.
  • Middleware can be applied globally (app.use) or to specific routes.

Need more clarification?

Drop us an email at career@quipoinfotech.com