Sunday, November 26, 2023

ExpressJS how to set a global variable

In Express.js, you can set global variables using the app.locals object. The app.locals object is an object that has properties that are local variables within the application. These variables are available to all middleware and routes in the application. Here's how you can set and access global variables in Express.js:


const express = require('express');

const app = express();


// Set a global variable

app.locals.myGlobalVariable = 'Hello, world!';


// Middleware that uses the global variable

app.use((req, res, next) => {

  console.log(`Global variable value: ${app.locals.myGlobalVariable}`);

  next();

});


// Route that uses the global variable

app.get('/', (req, res) => {

  res.send(`Global variable value: ${app.locals.myGlobalVariable}`);

});


app.listen(3000, () => {

  console.log('Server is running on port 3000');

});


In this example:


The app.locals.myGlobalVariable is set to a string.

The middleware and route both access the global variable using app.locals.

Keep in mind that using global variables should be done judiciously, as it can introduce coupling between different parts of your application. It's often preferable to pass necessary data explicitly through middleware and routes to maintain better separation of concerns.


If you need a more dynamic or shared global state across different instances of your application (for example, in a multi-process or multi-server environment), you might need to explore other options such as using a caching mechanism, a shared database, or a distributed data store.


References:

OpenAI


No comments:

Post a Comment