Birdman
Birdman

Reputation: 1524

How to access app.locals in other modules in NodeJS?

With my main server.js file, I exported my app variable:

//Assume there's other code in this file of course
    var app = express();
    app.locals.database = //here's my DB connection. This variable works perfectly within the server.js file!
    module.exports = app;

I imported it into another module:

var app = require('../server');

But I cannot access the app.locals variables? I set a few of them within my server.js (such as database connection info) but I get this error:

TypeError: Cannot read property 'database' of undefined

when trying to read:

app.locals.database

What am I doing wrong?

NOTE: In my other module app is {}, but when I check it within the originating module it has tons of info.

Upvotes: 1

Views: 4225

Answers (1)

1565986223
1565986223

Reputation: 6718

As per docs Once set, the value of app.locals properties persist throughout the life of the application.

In your case, as you've exported app, it's perfectly fine to access this at file level (not sure the right term), where you've imported as app.locals.database (remember app is an object).

But if you want to access elsewhere where you've not imported, express makes it available to all middleware via req.app.locals. The docs clearly mentions Local variables are available in middleware via req.app.locals

Also checkout this SO question, it give you a nice insight on app.locals and req.locals

Upvotes: 4

Related Questions