Why would I need template engines like Jade or EJS on the backend?

You actually dont need them, but they have a lot of features that makes your pages more dynamic..

For example you can render just HTML using this code

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

But with engines you can send data to template. http://expressjs.com/en/api.html#res.render

// pass a variable to the view
res.render('somePage', {
    title: 'Awesome title',
    userFriends: friendsList,
    name: 'loggedUserName'
});

And now on front-end templates(EJS in this case) will populate html with data that you send in. So html became dynamic and you can make each page looks different for each user.

<ul>
  <% for(var i=0; i<userFriends.length; i++) {%>
     <li><%= userFriends[i] %></li>
  <% } %>
</ul>

With just HTML you will need to make a lot of unnecessary AJAX calls to get and add data into html which is bad idea.

Hope this helps.


A view engine allows you to render HTML with options. For example, using squirrelly, I can create a file that looks like this:

<!DOCTYPE html>
<html>
  <head>
    <title>{{title}}</title>
  </head>
  <body>
   {(userIsSignedIn){<!-- if the user is signed in, display username and description-->
    <p>{{username}} is {{description}}</p>
    }}

    {(!userIsSignedIn){<!--if user isn't signed in, ask them to sign in-->
    <p>Sign in to view this page</p>
    }}

  </body>
</html>

So I could listen, for example, to a dynamic user profile URL with Express and then return dynamic content.


If you have data (say from a database) that needs to be rendered to HTML, you can use a template engine to take the data and a template and render it to HTML (which subsequently gets served to the client).

If your frontend app does the same, using XHR calls or something similar to retrieve the data from the server, it's generally not useful to render to HTML server side (instead, the data gets sent as JSON to the client).

So it depends on how your app (both frontend and backend) is structured if it makes sense or not to use a templating engine.

There's also hybrid solutions where the initial HTML is rendered server side, and then the client side "takes over". This is something that, for instance, React supports. The big idea there is that you can use the same components both on the server and on the client, and that when a page is opened, the user will get to see a fully rendered initial page (instead of the client side having to retrieve the data from the backend first and then rendering the page).