Categories
JavaScript Answers

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

Spread the love

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

For instance, we write

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

to set the app.locals.baseUrl property to the value we want.

Then we can get the value in our middlewares with

const baseUrl = req.app.locals.baseUrl;

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *