Categories
JavaScript Answers

How to pass variables to JavaScript in Express.js?

Spread the love

To pass variables to JavaScript in Express.js, we put a property in the context.

For instance, we write

app.get("/test.js", (req, res) => {
  res.set("Content-Type", "application/javascript");
  res.render("testPage", { myVar: "foo" });
});

to call res.render to render the testPage template.

We call it with an object with the variables we want to pass to the template.

Then we render the variable value with

<script>
  const myVar = <%- JSON.stringify(myVar) %>;
</script>

Conclusion

To pass variables to JavaScript in Express.js, we put a property in the context.

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 *