How do i set a variable in app.js
and have it be available in all the routes, atleast in the index.js
file located in routes. using the express framework and node.js

- 63,861
- 10
- 90
- 118

- 4,831
- 14
- 34
- 37
-
1The [app.locals](http://expressjs.com/pt-br/api.html#app.locals) object has properties that are local variables within the application. In your route file, reference it with `req.app.locals`. – Ronnie Royston Dec 24 '18 at 22:26
14 Answers
It is actually very easy to do this using the "set" and "get" methods available on an express object.
Example as follows, say you have a variable called config with your configuration related stuff that you want to be available in other places:
In app.js:
var config = require('./config');
app.configure(function() {
...
app.set('config', config);
...
}
In routes/index.js
exports.index = function(req, res){
var config = req.app.get('config');
// config is now available
...
}

- 1,449
- 1
- 11
- 10
-
Set 'app' global? Yes. But this method best for save us on problems and chaos. – diproart Apr 27 '14 at 13:09
-
75
-
Nice, `req.app.get('name')` works like a charm. This property holds a reference to the instance of the Express application that is using the middleware. http://expressjs.com/pt-br/api.html#req.app – Lazaro Fernandes Lima Suleiman Dec 28 '17 at 14:05
A neat way to do this is to use app.locals
provided by Express itself.
Here is the documentation.
// In app.js:
app.locals.variable_you_need = 42;
// In index.js
exports.route = function(req, res){
var variable_i_needed = req.app.locals.variable_you_need;
}

- 2,228
- 1
- 21
- 21
-
1I used this method to locate http services and easily override in unit tests. – Alex Nov 14 '17 at 11:51
-
-
@MoisesRodan - You may find `res.locals` more useful if you just want the value persisted for the request – Lee Goddard Jun 11 '21 at 11:54
To make a global variable, just declare it without the var
keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.)
Here's an example from visionmedia/screenshot-app
file app.js:
/**
* Module dependencies.
*/
var express = require('express')
, stylus = require('stylus')
, redis = require('redis')
, http = require('http');
app = express();
//... require() route files
file routes/main.js
//we can now access 'app' without redeclaring it or passing it in...
/*
* GET home page.
*/
app.get('/', function(req, res, next){
res.render('index');
});
//...

- 2,188
- 1
- 23
- 28
-
7As a note, it's generally better to be explicit about passing variables around and instantiating them, so you don't accidentally null out the ref somewhere else in the app, or what have you. – Paul Sep 06 '12 at 17:45
-
4This is really bad form, as Paul noted. I would suggest the injection pattern mentioned below. Yes, more boiler plate code so it doesn't look "pretty" but it ensures your code is modular... something you'll like if this isn't your last project ;) – srquinn Jan 15 '13 at 01:23
-
It depends on the circumstances IMHO. Yes, global vars are generally not a good practice (as I stated in my answer) and when starting from scratch, I'd say organize everything into separate modules. But if you're integrating with existing code, there are often other considerations - this just happens to be one (easy, yet dangerous) solution. – Jesse Fulton Feb 12 '13 at 23:51
-
3Could someone explain why this works in reference to Javascript's semantics? Which scope does `app` get associated to? – Ali Feb 08 '16 at 10:52
-
2
-
@Ali - Global scope is accessed via `global` in Node (`window` in browsers), and the answer should reflect that to highlight that `app` is global (`global.app`). – Lee Goddard Jun 11 '21 at 11:53
To declare a global variable you need do use global object. Like global.yourVariableName. But it is not a true way. To share variables between modules try to use injection style like
someModule.js:
module.exports = function(injectedVariable) {
return {
somePublicMethod: function() {
},
anotherPublicMethod: function() {
},
};
};
app.js
var someModule = require('./someModule')(someSharedVariable);
Or you may use surrogate object to do that. Like hub.
someModule.js:
var hub = require('hub');
module.somePublicMethod = function() {
// We can use hub.db here
};
module.anotherPublicMethod = function() {
};
app.js
var hub = require('hub');
hub.db = dbConnection;
var someModule = require('./someModule');

- 33,439
- 9
- 77
- 71

- 25,689
- 4
- 56
- 48
the easiest way is to declare a global variable in your app.js, early on:
global.mySpecialVariable = "something"
then in any routes you can get it:
console.log(mySpecialVariable)

- 111
- 1
- 4
-
1In Express - when using jshint or linting, in general - this becomes a problem. – Steven Ventimiglia Mar 22 '19 at 15:45
-
1It's bad practice, but it is you who tell the linter what to do, and one could tell it not to make a noise about global. – Lee Goddard Jun 11 '21 at 11:55
-
It's a problem regardless of what the linters say. This may be the "easiest" way, but it's technical debt that you'll have to pay back later when you have name clashes and bugs from referencing the wrong variable somewhere, or need to refactor code to work with a test suite, etc. – ggorlen May 25 '22 at 01:02
This was a helpful question, but could be more so by giving actual code examples. Even the linked article does not actually show an implementation. I, therefore, humbly submit:
In your app.js
file, the top of the file:
var express = require('express')
, http = require('http')
, path = require('path');
app = express(); //IMPORTANT! define the global app variable prior to requiring routes!
var routes = require('./routes');
app.js will not have any reference to app.get()
method. Leave these to be defined in the individual routes files.
routes/index.js
:
require('./main');
require('./users');
and finally, an actual routes file, routes/main.js
:
function index (request, response) {
response.render('index', { title: 'Express' });
}
app.get('/',index); // <-- define the routes here now, thanks to the global app variable

- 2,181
- 5
- 28
- 47
Here are explain well, in short:
http://www.hacksparrow.com/global-variables-in-node-js.html
So you are working with a set of Node modules, maybe a framework like Express.js, and suddenly feel the need to make some variables global. How do you make variables global in Node.js?
The most common advice to this one is to either "declare the variable without the var keyword" or "add the variable to the global object" or "add the variable to the GLOBAL object". Which one do you use?
First off, let's analyze the global object. Open a terminal, start a Node REPL (prompt).
> global.name
undefined
> global.name = 'El Capitan'
> global.name
'El Capitan'
> GLOBAL.name
'El Capitan'
> delete global.name
true
> GLOBAL.name
undefined
> name = 'El Capitan'
'El Capitan'
> global.name
'El Capitan'
> GLOBAL.name
'El Capitan'
> var name = 'Sparrow'
undefined
> global.name
'Sparrow'

- 158,873
- 26
- 254
- 302

- 133
- 1
- 3
-
In Express - when using jshint or linting, in general - this becomes a problem. – Steven Ventimiglia Mar 22 '19 at 15:44
-
Needn't be a problem in linting. But why is this only half an answer? Where's the rest? – Lee Goddard Jun 11 '21 at 11:56
My preferred way is to use circular dependencies*, which node supports
- in app.js define
var app = module.exports = express();
as your first order of business - Now any module required after the fact can
var app = require('./app')
to access it
app.js
var express = require('express');
var app = module.exports = express(); //now app.js can be required to bring app into any file
//some app/middleware, config, setup, etc, including app.use(app.router)
require('./routes'); //module.exports must be defined before this line
routes/index.js
var app = require('./app');
app.get('/', function(req, res, next) {
res.render('index');
});
//require in some other route files...each of which requires app independently
require('./user');
require('./blog');

- 17,181
- 5
- 36
- 22
-
Great tip. I just moved from the require('./myroutes')(app) method to doing this and hit my head against a wall for 10 minutes trying to figure out why none of my routes worked. Don't forget to take route specifications in myroutes.js out of a function block. Doh! – greg Mar 17 '16 at 04:04
this is pretty easy thing, but people's answers are confusing and complex at the same time.
let me show you how you can set global variable in your express
app. So you can access it from any route as needed.
Let's say you want set a global variable from your main /
route
router.get('/', (req, res, next) => {
req.app.locals.somethingNew = "Hi setting new global var";
});
So you'll get req.app from all the routes. and then you'll have to use the locals
to set global data into. like above show you're all set. now
I will show you how to use that data
router.get('/register', (req, res, next) => {
console.log(req.app.locals.somethingNew);
});
Like above from register
route you're accessing the data has been set earlier.
This is how you can get this thing working!

- 881
- 14
- 19
const app = require('express')();
app.set('globalvar', "xyz");
app.get('globalvar');

- 1,753
- 1
- 18
- 26
-
2Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Feb 22 '22 at 22:19
-
2hm... setting and getting global variables? not sure how much more needed – MartianMartian Feb 23 '22 at 11:36
As others have already shared, app.set('config', config)
is great for this. I just wanted to add something that I didn't see in existing answers that is quite important. A Node.js instance is shared across all requests, so while it may be very practical to share some config
or router
object globally, storing runtime data globally will be available across requests and users. Consider this very simple example:
var express = require('express');
var app = express();
app.get('/foo', function(req, res) {
app.set('message', "Welcome to foo!");
res.send(app.get('message'));
});
app.get('/bar', function(req, res) {
app.set('message', "Welcome to bar!");
// some long running async function
var foo = function() {
res.send(app.get('message'));
};
setTimeout(foo, 1000);
});
app.listen(3000);
If you visit /bar
and another request hits /foo
, your message will be "Welcome to foo!". This is a silly example, but it gets the point across.
There are some interesting points about this at Why do different node.js sessions share variables?.

- 1
- 1

- 7,851
- 4
- 46
- 76
I used app.all
The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches.
In my case, I'm using confit for configuration management,
app.all('*', function (req, res, next) {
confit(basedir).create(function (err, config) {
if (err) {
throw new Error('Failed to load configuration ', err);
}
app.set('config', config);
next();
});
});
In routes, you simply do req.app.get('config').get('cookie');

- 14,131
- 7
- 65
- 79
I solved the same problem, but I had to write more code.
I created a server.js
file, that uses express to register routes.
It exposes a function,register
, that can be used by other modules to register their own routes.
It also exposes a function, startServer
, to start listening to a port
server.js
const express = require('express');
const app = express();
const register = (path,method,callback) => methodCalled(path, method, callback)
const methodCalled = (path, method, cb) => {
switch (method) {
case 'get':
app.get(path, (req, res) => cb(req, res))
break;
...
...
default:
console.log("there has been an error");
}
}
const startServer = (port) => app.listen(port, () => {console.log(`successfully started at ${port}`)})
module.exports = {
register,
startServer
}
In another module, use this file to create a route.
help.js
const app = require('../server');
const registerHelp = () => {
app.register('/help','get',(req, res) => {
res.send("This is the help section")
}),
app.register('/help','post',(req, res) => {
res.send("This is the help section")
})}
module.exports = {
registerHelp
}
In the main file, bootstrap both.
app.js
require('./server').startServer(7000)
require('./web/help').registerHelp()

- 1,360
- 2
- 18
- 38
John Gordon's answer was the first of dozens of half-explained / documented answers I tried, from many, many sites, that actually worked. Thank You Mr Gordon. Sorry I don't have the points to up-tick your answer.
I would like to add, for other newbies to node-route-file-splitting, that the use of the anonymous function for 'index' is what one will more often see, so using John's example for the main.js, the functionally-equivalent code one would normally find is:
app.get('/',(req, res) {
res.render('index', { title: 'Express' });
});

- 668
- 10
- 18