Nodejs express – Persist variables across the app life

If you have created an application using Nodejs + express, you may want to utilize global variables whose values change at runtime. If you are utilizing multiple child processes (using fork), you may even desire a scenario where one child process modifies the value of a variable, and it gets reflected across child processes. You can achieve this as follows.

Declare your variable as app.locals.variable name. For example:

'use strict';
let express = require('express');

var app = express();

app.locals.token = "";

As you can see, we haven’t used var or let before the declaration.

Next, edit the value of that variable wherever required in the code. For example:

app.get('/', async function (req, res) {
  console.log(req);
  if(req.query.hasOwnProperty('token')){
    app.locals.token = req.query.token;
  }
  res.end(JSON.stringify({ "status": "Success", "token":app.locals.token.toString()}))
})

That’s it. You can do this for as many variables as you like. In order to test this out, you can deploy the app (complete code below), then invoke http://localhost:8081/, followed by http://localhost:8081/?token=abcd, followed again by http://localhost:8081/. The output you will get in the third invocation is:

{"status":"Success","token":"abcd"}

You will see the token persisted across the session, even when you did not specify it in the query params.

Complete code:

'use strict';
let express = require('express');
var app = express();

app.locals.token = "";

app.get('/', async function (req, res) {
    console.log(req);
    if (req.query.hasOwnProperty('token')) {
        app.locals.token = req.query.token;
    }
    res.end(JSON.stringify({ "status": "Success", "token": app.locals.token.toString() }))
})

var server = app.listen(process.env.PORT || 8081, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
})

Note that these variables’ values persist throughout the life of the application. Only when the application restarts will the values of these variables be reset. This is in contrast to res.locals, which is persisted only through the lifetime of a request. You can get a good comparison between app.locals and res.locals in the following StackOverflow threads:

  1. app.locals and res.locals lifecycle
  2. What’s the difference between app.locals, res.locals and req.app.locals

I hope you liked this article. For more articles on IoT in general, check out https://iotespresso.com/

Leave a comment

Your email address will not be published.