0
\$\begingroup\$

I have an Express server. It serves a static HTML file that uses Vue.

I don't want to render the HTML in NodeJS (e.g., using Pug), Vue already renders it on the client side and spares my server's resources. But it requires some dynamic data. Instead of polling the server for this data after the DOM is loaded, I'm injecting it into the HTML file in NodeJS:

const htmlFile = await fs.promises.readFile('htmlFile', 'utf8'),
    myData = [object1, object2, object3, etc],
    // Try to sanitize my data only by replacing <>
    myDataLazilySanitized = (JSON.stringify(myData)).replace(/[<>]/g, (char) => char === '<' ? '&lt;' : '&gt;');

// I now add myData to a custom element, right after the <body> tag
res.send(htmlFile.replace(/<body>/i, '<body><x-server-data id="x-server-data" class="hidden">' + myDataLazilySanitized + '</x-server-data>'));

Nothing in myData has < or >, so I can safely replace them for HTML entities.

The browser then parses this data:

myData = JSON.parse(document.getElementById('x-server-data').innerHTML);

I have 2 questions:

  • Is it safe what I'm doing? (i.e., is this lazy sanitizing enough)
  • Is there an easier way to do this?

Realted:
https://stackoverflow.com/questions/58264703/nodejs-how-to-insert-an-element-in-a-html-document-using-javascript

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.