Search code examples
node.jsejs

EJS Interpolation: Variable not defined when used inside script tag


My variable can be used while outside script tag, but not from the inside.

Route.ts

router.get('/myRoute/:myId', async (req: Request, res: Response, next: NextFunction)=> {
const userData = {
  name: 'blabla',
  age: 22
}

res.status(200).render('myPage', { userData });
});

myPage.ejs

<html>
<head>
<% console.log(userData) %> // Log the content without a problem

<script>
  console.log(userData) // THROWS ERROR: userData not defined
</script>
</head>

How may I use this interpolatio from the inside of script tags?


Solution

  • that would be because outside the script using <% %> it's rendered server side (in node), while inside the script it's rendered client side (in the browser)

    and if you check the script in the browser you will notice that no variable userData has been defined

    you want declare the variable in the script tag and parse it

    <script>
     //if it's a json object
     const userData = JSON.parse('<%- JSON.stringify(userData) %>')
     //if it's a normal variable
     const userData1 = '<%- userData %>'
    </script>