Search code examples
htmlnode.jsexpressnodejs-server

How to i use the variable from express in html?


I have this in express

app.get('/', requiresAuth(), (req, res) =>
    res.sendFile('/db_auth_site/index.html', { title: 'Hey', message: 'Hello there!' })
);

How can i use title in html like?

<h1>title variable here</h1>

Solution

  • You can't per se. HTML doesn't have that capability.

    You need to use a template language such as Nunjucks, EJS, or Mustache.

    The Express documentation has a section that covers using Pug and MDN has a more detailed guide.

    Other template languages are similar, you just change the modules you install and the view engine setting then use the syntax of the template language you picked.

    Note that most template languages are "The language you want to output with special tags inside" but Pug is very much an exception. If you want to write something that looks like HTML, don't use Pug.

    You also need to use render instead of sendFile.