How to create global variables accessible in all views using Express and Node.js?

Sometimes, we want to create global variables accessible in all views using Express and Node.js.

In this article, we’ll look at how to create global variables accessible in all views using Express and Node.js.

How to create global variables accessible in all views using Express and Node.js?

To create global variables accessible in all views using Express and Node.js, we can set the app.locals property.

For instance, we write

app.locals.baseUrl = "http://www.example.com"

to set app.locals.baseUrl to a string.

Then we can access the baseUrl string with

req.app.locals.baseUrl

in our middleware functions.

Conclusion

To create global variables accessible in all views using Express and Node.js, we can set the app.locals property.