How to access Express.js local variables in client side JavaScript?

Sometimes, we want to access Express.js local variables in client side JavaScript.

In this article, we’ll look at how to access Express.js local variables in client side JavaScript.

How to access Express.js local variables in client side JavaScript?

To access Express.js local variables in client side JavaScript, we can call res.render with an object with the variables.

Then we can reference them in the template.

For instance, we write

res.render('search-directory', {
  title: 'My Title',
  placeUrls: JSON.stringify(placeUrls),
});

to call res.render with an object with the local variables in the 2nd argument.

Then we write

search-directory.jade

script(type='text/javascript').
    const urls =!{placeUrls}

to add a script tag which assigns urls to the placeUrls JSON string.

The string will be interpolate as a JavaScript object.

Conclusion

To access Express.js local variables in client side JavaScript, we can call res.render with an object with the variables.