Daily : Wed 26th of June : Express and passing variables

Alessandro - Jun 27 - - Dev Community

Hi everyone,

After starting to explore Express yesterday, I tried to delve deeper into the concept of routes. I wanted to understand how we could pass a variable between multiple middlewares, to do something like logging information that isn't in req.params into a log file.

The answer is quite simple, but I thought it would be helpful to share it with you in this quick blog post.

Here's the index.js code:

console.log('Express Exercises');

import food from './routes/food.js';

const app = express();
const port = 3000;

app.use(food);

app.listen(port, () => {
    console.log(`Listening on ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

And here is the food.js route code stored in the routes directory, showing how you can pass a variable to a log function:

import express from 'express';

const router = express.Router();

const response = (req, res, next) => {
    res.send(`Url: ${req.originalUrl}`);
    req.toLog = 'valuefromResponse';
    next();
};
const setLog = (req, res, next) => {
    console.log(`${req.method} : ${req.toLog}`);
};

router.use(response);
router.use(setLog);

router.get('/food', [response, setLog]);

export default router;
Enter fullscreen mode Exit fullscreen mode

When you execute a GET request to http://localhost:3000/food, here's the console output:

GET : valueFromResponse
Enter fullscreen mode Exit fullscreen mode

There you have it! I hope this gives you a little idea of how to use this in your future projects.

See you soon! 😊

. . . . .