Skip to content
Advertisement

How do I pass objects from NodeJS to javascript files with EJS

Down below you can see I have a nodeJS server which passes down a data object to the index page. Inside of my index.ejs file I can receive this data using <%= data %> however this only gives [object Object]. However, what I want is to receive this data inside my javascript file as an acutal object so I can use the data to do stuff. How can I acheive this?

NodeJS:

router.get("/", getData, (req, res) => {
  res.render("index", { data: data }); // Where 'data' is a large object with lots of information 
});

index.ejs:

<html>
  <head>
    ...
    <script defer src="myScript.js"></script> <!-- I want to pass the data object to this file -->
  </head>
  <body>
    <%= data %> <!-- This works, but is not what I want -->
  </body>
</html>

myScript.js:

const data = <%= data %> // this doesnt work, but is what I need

Advertisement

Answer

JSON is a data exchange language based on literal syntax for JavaScript. So long as your data consists entirely of data types supported by JSON (such as plain objects and numbers) you can use it to generate a string that you can insert into a data attribute and parse with `JSON.parse.

<script data-data="<%= JSON.stringify(data) %>">
    const data = JSON.parse(document.currentScript.dataset.data);
</script>

If your object includes features not supported by JSON, such as functions, symbols, etc. then you’ll need to special case how they are transferred across.


An earlier version of this answer used a similar technique that treated the JSON as JavaScript source code. This more-or-less works, but is vulnerable to XSS since if the data contains a string "</script>" that will terminate the script element in the middle of the string literal. There is a potential that further data in the string could pose a more serious XSS threat.

You could use that technique, but you would need to mitigate that attack by escaping / characters.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement