express pass data between middleware

To pass data between middleware in Express, you can use the req and res objects. Here are the steps:

  1. Define your middleware function using the app.use() method. This function will have access to the req, res, and next parameters, representing the request, response, and the next middleware function in the stack.

  2. Inside the middleware function, you can store data on the req object using req.propertyName = value. This will make the data available to subsequent middleware functions or routes.

  3. If you want to pass data to the next middleware function in the stack, you can call next() without any arguments. This will continue the execution flow to the next middleware.

  4. To access the data passed from the previous middleware, you can use req.propertyName in subsequent middleware functions or routes.

Here's an example to illustrate the steps:

const express = require('express');
const app = express();

// Middleware function
const myMiddleware = (req, res, next) => {
  req.myData = 'Hello from middleware!';
  next();
};

// Route
app.get('/', (req, res) => {
  console.log(req.myData); // Output: 'Hello from middleware!'
  res.send('Response from route');
});

app.use(myMiddleware);

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In this example, the myMiddleware function is defined to add the myData property to the req object. The route handler then accesses this data using req.myData.

By following these steps, you can easily pass data between middleware functions in Express.