Accessing Global Variables within Routes in Express

Viewed 371

I'm still new to Express, so please bear with me.

What I'm trying to do is store some of my environmental variables in a global variable such that they can be accessed in any route without having to redeclare the variables within each route.

Note that I used the Express Generator to set up the project scaffolding.

Here's a stripped-down example of what I'm trying to do:

App.js

const express = require('express');

// Load Routes
const inventoryRouter = require('./src/routes/inventory');

// Instantiate Express/Assign App Var
const app = express();

// Set Global Env Vars
app.set('DevUrl', process.env.Dev_URL || null);

// Use Routes
app.use('/inventory', inventoryRouter);

module.exports = app;

Inventory.js

const express = require('express');
const router = express.Router();

// Require Inventory Controller
const inventoryController = require('../controllers/inventoryController');

// Inventory Routes
router.get('/', inventoryController.get_inventory);
router.post('/', inventoryController.update_inventory);

module.exports = router;

InventoryController.js

const router = express.Router();

// Store Vars
const LocalRouteVariable = app.get('DevUrl') + 'Some String';

// Rest of Controller Code ...

Question "app" is not defined in the controller. So, my question is, how can I get the value of "DevUrl"?

1 Answers

You can use req.app to access the app instance from inside a controller.

In your case:

InventoryController.js

export get_inventory = async (req, res, next) =>{
   const devUrl = req.app.get('DevUrl');
   //Controller Logic
}
Related