Mechanisms and Practices of Variable Passing Between Node.js and HTML

Dec 01, 2025 · Programming · 10 views · 7.8

Keywords: Node.js | HTML | variable passing | Express | EJS template engine

Abstract: This article explores the core mechanisms of passing variables from Node.js back-end to HTML front-end, focusing on the implementation using Express framework's res.render() method with template engines. It details two main approaches with EJS template engine: embedding JavaScript variables in HTML and directly rendering HTML content, illustrated with code examples. The article also compares alternative solutions like Pug template engine, providing complete configuration and usage guidelines to help developers understand the fundamentals and best practices of server-side rendering.

Fundamental Principles of Variable Passing Between Node.js and HTML

In modern web development, data transfer between server-side and client-side is a core aspect of building dynamic applications. Node.js, as a popular JavaScript runtime environment, provides flexible mechanisms through frameworks like Express to achieve this goal. This article delves into how to pass variables from Node.js back-end to HTML front-end, with a focus on template engine-based solutions.

The res.render() Method in Express Framework

The res.render() method in Express framework is the key interface for server-side rendering. This method accepts two main parameters: the view file path and a data object containing variables. Here is a basic example:

app.get('/main', function(req, res) {
  var name = 'hello';
  res.render(__dirname + "/views/layouts/main.html", {name:name});
});

In this example, the name variable is passed to the view file named main.html. The Express framework itself does not directly handle variable substitution in HTML files; this requires the assistance of a template engine.

Two Implementation Approaches Using EJS Template Engine

Approach 1: Embedding JavaScript Variables in HTML

According to the best answer solution, variables can be received and utilized in HTML files using EJS template syntax:

<script>var name = "<%= name %>";</script>
console.log(name);

The core of this approach is embedding <script> tags in the HTML file and using the <%= name %> syntax to inject the server-side name variable value into client-side JavaScript. When Express renders this HTML file, the EJS engine replaces <%= name %> with the actual variable value (in this case, "hello"), generating executable JavaScript code for the browser.

Approach 2: Directly Rendering HTML Content

Another common approach is to directly use passed variables to generate content in HTML templates:

<h1><%= name %></h1>

This method more directly embeds variable values into HTML structure, suitable for scenarios requiring dynamic content display on pages. To implement this method, Express must be correctly configured to use EJS as the rendering engine for HTML files:

app.engine('html', require('ejs').renderFile);

This line of code instructs Express to use the EJS engine to process .html files, enabling it to parse template syntax and perform variable substitution.

Complete Configuration and Implementation Steps

To ensure the above methods work correctly, complete project configuration is necessary. Here is a more comprehensive example:

var express = require('express');
var app = express();

// Configure EJS as template engine for HTML files
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

// Define route
app.get('/main', function(req, res) {
  var name = 'hello';
  res.render('layouts/main', {name:name});
});

In this configuration, app.set('views', __dirname + '/views') specifies the directory for view files, allowing res.render() to locate files based on relative paths. This configuration approach enhances code maintainability and readability.

Alternative Solution: Pug Template Engine

Besides EJS, Pug (formerly Jade) is another popular template engine choice. Here are the basic steps for using Pug:

  1. Install Pug dependency: npm install --save pug
  2. Configure Express to use Pug: app.set('view engine', 'pug');
  3. Create Pug template file (e.g., index.pug):
html
  head
    title= title
  body
    h1= message
<ol start="4">
  • Render template in route:
  • app.get('/', function (req, res) {
      res.render('index', { title: 'Hey', message: 'Hello there!'});
    });

    Pug uses concise indentation-based syntax, offering a different expression style compared to traditional HTML. The choice between EJS and Pug primarily depends on project requirements and personal preference.

    Security Considerations and Best Practices

    When passing variables from server to client, security considerations are essential. Particularly when variable values come from user input, cross-site scripting (XSS) attacks must be prevented. EJS's <%= %> syntax defaults to HTML escaping of output, providing some security protection. For example:

    <script>var userInput = "<%= unsafeData %>";</script>

    If unsafeData contains <script>alert('xss')</script>, EJS will escape it to &lt;script&gt;alert('xss')&lt;/script&gt;, preventing script execution.

    For cases requiring raw HTML output, the <%- %> syntax can be used, but data source must be completely trusted:

    <div><%- trustedHTML %></div>

    Conclusion and Extended Applications

    Passing variables between Node.js and HTML through template engines is a fundamental technology in modern web development. The EJS methods introduced in this article are easy to learn due to their near-native HTML syntax while providing necessary security features. In practical projects, developers can choose different template engines based on needs and consider combining with other technologies like AJAX or WebSocket for more complex real-time data interaction.

    Understanding these core concepts not only helps implement basic variable passing but also lays the foundation for building more advanced server-side rendering applications. As front-end technology evolves, these principles remain valuable in modern frameworks like Next.js and Nuxt.js.

    Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.