Third-party middleware helps add ready-made features to your Node.js app easily. It saves time by handling common tasks for you.
0
0
Third-party middleware usage in Node.js
Introduction
You want to log all requests to your server without writing your own code.
You need to parse incoming JSON data from users automatically.
You want to handle cookies or sessions without building it from scratch.
You want to add security features like helmet to protect your app.
You want to compress responses to make your app faster.
Syntax
Node.js
import express from 'express'; import middlewareName from 'middleware-package'; const app = express(); app.use(middlewareName(options));
Use import to bring in the middleware package.
Call app.use() to add the middleware to your app.
Examples
This adds the
morgan logger middleware to log requests in 'dev' format.Node.js
import express from 'express'; import morgan from 'morgan'; const app = express(); app.use(morgan('dev'));
This adds
cors middleware to allow cross-origin requests.Node.js
import express from 'express'; import cors from 'cors'; const app = express(); app.use(cors());
This adds
helmet middleware to improve security by setting HTTP headers.Node.js
import express from 'express'; import helmet from 'helmet'; const app = express(); app.use(helmet());
Sample Program
This program uses the morgan middleware to log each request in a short format. When you visit the root URL, it responds with a greeting message.
Node.js
import express from 'express'; import morgan from 'morgan'; const app = express(); // Use morgan middleware to log requests app.use(morgan('tiny')); app.get('/', (req, res) => { res.send('Hello from middleware example!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Always install the middleware package first using npm install package-name.
Middleware order matters: put middleware that parses data before routes that use that data.
Some middleware needs options to work properly; check the package docs.
Summary
Third-party middleware adds useful features without extra coding.
Use app.use() to add middleware to your Express app.
Pick middleware based on what your app needs, like logging, security, or parsing.