Skip to content

Instantly share code, notes, and snippets.

@danschumann
Last active January 4, 2021 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danschumann/ae0b5bdcf2e1cd1f4b61 to your computer and use it in GitHub Desktop.
Save danschumann/ae0b5bdcf2e1cd1f4b61 to your computer and use it in GitHub Desktop.
How to pass an object from nodejs to frontend
myObject = { ... }
this.injectString = JSON.stringify( myObject ).replace(/\\/g, '\\\\').replace(/"/g, '\\\"')
We only worry about parsing now, since everything should have been properly escaped
<script>
window.myObjectFrontend = JSON.parse("<%- @injectString %>");
</script>
@danschumann
Copy link
Author

This is for passing an object directly from the backend into a script tag so it can be used on the frontend

@danschumann
Copy link
Author

Note: basically all we do is escape slashes and double quotes.

Notice how we're parsing on the frontend, so we have our object back. In the frontend parse method, we use double quotes, so we have to escape those in the stringified string.

@danschumann
Copy link
Author

myObject == myObjectFrontend // true, except one is frontend and one is backend

@danschumann
Copy link
Author

We replace \ with \\ and " with \" so that it can be 1 string when it is printed in html
We are replacing because it needs to be passed to frontend through JSON.parse("{{injectString}}"); ( note the " wrapping the backend string ).
"{"mykey":"my\"val"}" -- pre-regex -- not parseable, the frontend sees this as 4 strings with junk in between
"{\"mykey\":\"my\\\"val\"}" -- post-regex -- parseable
the first replace is for my\"val, since the second replace would cause that to break. If only the second replace was applied, it would become my\\"val means it escapes a slash, and the double quotes would end the parse string prematurely. Applying both regexes makes it my\\\"val, the first two slashes make one slash, and the third escapes the ", making it identical to my\"val when printed

@agm1984
Copy link

agm1984 commented Sep 6, 2017

Here's how I did it for an array:

Backend

const response = await request(GRAPHQL_ENDPOINT, query)
return res.render('research/index', {
    articles: JSON.stringify(response.getAllArticles) || [] // Stringify output to Frontend
})

Frontend

<script>
    window.quillContent = <%- articles.replace(/=&gt;/g, '=>') %> // I had to fix => back to fat arrow
</script>

<% const allArticles = JSON.parse(articles)
allArticles.forEach((article, i) => { %>
        <div id="editor<%- i %>"></div> // Create dynamic number of divs
<% }) %>

<script>
    'use strict'

    hljs.configure({
        languages: ['javascript']
    })

    window.quillContent.forEach((article, i) => {
        const quill = new Quill(`#editor${i}`, { // Create dynamic number of Quill Editors
            modules: {
                syntax: true,
                toolbar: false
            },
            readOnly: true,
            theme: 'snow'
        })
        quill.setContents(JSON.parse(window.quillContent[i].content)) // Parse input from Backend
    })
</script>

This code is specific to Quill when using syntax highlighting on ES6 code, but it demonstrates iterating through the array in a common manner.

The basics are the same: JSON.stringify() Array output to Frontend, and then JSON.parse() the Array in the Frontend when you consume it, and you may see some HTML entities get leaked in (which is feeling like an EJS templating engine issue).

@danschumann
Copy link
Author

  @if(isset($payload))
    {{--*/
      $payload = json_encode($payload);
      $payload = preg_replace("_\\\_", "\\\\\\", $payload);
      $payload = preg_replace("/\"/", "\\\"", $payload);
    /*--}}
    <script>
      window.__payload = JSON.parse("{!!$payload!!}");
    </script>
  @endif

Here's a php blade version. Payload is any object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment