Search code examples
javascriptnode.jspugweb-deployment

Syntax Error passing a variable from index.js in node.js


I'm developing a web mapping site which uses node.js and pug as its templating engine. I'm trying to pass in a variable from index.js to my map.pug file, specifically a user parameter which contains Google login info when a user is logged into the site.

The index.js code snippet is:

app.get('/map', (req,res) => {
    res.render('map', {
        user: req.user,
        authenticated: req.isAuthenticated()
    });
});

The map.pug snippet is:

var user
// Find out if the user is logged in & assign to "user" variable if so
if (!{JSON.stringify(authenticated)} == true) {
    user = !{JSON.stringify(user)};
} else {
    user = 'undefined';
};
console.log(user);

This works fine when the user is logged in as it passes a dictionary through to the user variable. When the user isn't logged in, req.user is undefined and so doesn't pass anything through to user.

This results in the following Syntax Error:

Uncaught SyntaxError: Unexpected token ';'

Even though the JSON.stringify statement is in an if statement? I've tried using try...catch, to fix this but it doesn't work for syntax errors so I'm a little stuck on how to fix this issue.


Solution

  • As you mentioned the issue is due to the user variable not being set when they aren't authenticated. (Which causes the rendered script on the page to have user = ; which is a syntax error). You can solve this by setting a default value if req.user is undefined in the express render function.

    app.get('/map', (req, res) => {
        res.render('map', {
            authenticated: req.isAuthenticated(),
            user: req.user !== undefined ? req.user : {},
        })
    });
    

    The above will set user to an empty object when it is undefined