Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing a variable between 2 routes express

I wanted to know if there is a way to share variables between 2 routes in expressJS without declaring it as a global. Consider I have the following routes:

exports.routeOne = (req,res) => { 
 var myVariable='this is the variable to be shared';
}

exports.routeTwo = (req,res) => {
  //need to access myVariable here
}

How can this be done ?

like image 922
Anirudh Mittal Avatar asked May 14 '26 21:05

Anirudh Mittal


1 Answers

===============

Note

This answer is answering the wrong question, but it might still be useful for others who also misinterpreted the question like I did, so I'm keeping it here for now.

===============

In order for the variable to exist it would have to first execute routeOne and then execute routeTwo. This is a pretty common scenario with express. To get the details on how this works read up on middleware (http://expressjs.com/en/guide/writing-middleware.html) and understand that each route is middleware.

The common pattern solution here is to add a new property to either the req or res object that stores your variable. Then you tell the route to call the next middleware. The next middleware has access to the same req and res so it also has access to the property and value that you just stored.

There is nothing wrong with this practice as most middleware does it. For example the body-parser middleware (https://www.npmjs.com/package/body-parser).

Here is an example of how your code might run:

routes.js

exports.routeOne = (req,res,next) => { 
 req.myVariable='this is the variable to be shared'
 next()
}

exports.routeTwo = (req,res) => {
  //need to access myVariable here
  console.log(req.myVariable)
}

index.js

const express = require('express')
const routes = require('./routes.js)

const app = express()
app.use(routes.routeOne)
app.use(routes.routeTwo)

app.listen(3000)
like image 54
James Avatar answered May 16 '26 09:05

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!