
30/10/2024
Middleware is a function that has access to the request (req), response (res), and the next middleware function in the application's request-response cycle. It can execute code, make changes to the request and response objects, end the request-response cycle, and call the next middleware function to continue processing.
Let's walk through creating a simple logging middleware that will log the details of each incoming request.
Initialize Your Project: If you haven’t already, create a new directory for your project and initialize Node.js:
mkdir express-middleware-example cd express-middleware-example npm init -y
Install Express: Install Express.js via npm:
npm install express
Create Your Server File: Create a file named server.js:
touch server.js
In your server.js file, start by importing Express and then set up your basic server:
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000;
Now, let's create our custom logging middleware:
const loggerMiddleware = (req, res, next) => { console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); next(); // Pass control to the next middleware or route handler };
To use the middleware we've just created, add it to your Express application like so:
app.use(loggerMiddleware); // Register the middleware app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Now that everything is set up, you can run your server:
node server.js
Open your web browser and navigate to http://localhost:3000. You should see "Hello, World!" displayed. In your terminal, you will also see the log from your middleware stating the HTTP method and URL of the request.
Whenever you need to perform specific tasks, you can adjust your middleware. Here are few examples of what you can log or manipulate:
Log Headers:
console.log(req.headers);
Check for Authorization:
if (!req.headers.authorization) { return res.status(403).send('Forbidden'); }
Measure Request Duration:
const startTime = Date.now(); next(); const duration = Date.now() - startTime; console.log(`Request took ${duration}ms`);
By now, you've seen how easy it is to create a custom middleware in Express.js that enhances your application functionality while keeping your code clean and organized. Middleware is a powerful feature that you'll find essential as your application grows. Don't hesitate to explore even more complex middleware tailored to your application's specific needs!
30/10/2024 | DotNet
30/10/2024 | DotNet
30/10/2024 | DotNet
30/10/2024 | DotNet
30/10/2024 | DotNet
30/10/2024 | DotNet