Open In App

How to Pass variables to JavaScript in Express JS ?

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Express is a lightweight framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. When working with Express.js you may encounter scenarios where you need to pass variables from your server-side code to client-side JavaScript.

In this article will guide you through the steps of passing variables to JavaScript in Express.js with examples.

ExpressJS seamlessly integrates with template engines like EJS (Embedded JavaScript), allowing you to embed JavaScript code directly into HTML templates. This makes it easy to pass variables from the backend to the frontend during template rendering.

Steps to create Express Application

Step 1: Initialize your project via the following command

npm init -y

Step 2: Install ExpressJS and Embedded JavaScript (EJS)

npm install express ejs 

Project Structure:

Screenshot-(762)

The updated dependencies in packages.json file will look like:

"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.3"
}

Example 1: This Example demonstrates how to pass variables to JS in ExpressJS

HTML
<!-- views/index.ejs -->

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Express.js Variable Passing</title>
</head>

<body>
    <h1>Welcome to Express.js Variable Passing</h1>
    <script>
        const greeting = "<%= message %>";
        console.log(greeting);
    </script>
</body>

</html>
Javascript
//app.js

import express from "express";

const app = express();
const port = 3000;

app.set("view engine", "ejs");

app.get("/", (req, res) => {
    const message = "Hello from Express!";
    res.render("index", { message });
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Output:

Screenshot-(763)

Example 2: In this example we are making a simple HTTP request to a public JSONPlaceholder API and passing variable

HTML
<!-- views/index.ejs -->

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
    <title>Express.js Dynamic Book List</title>
</head>

<body>
    <h1>Dynamic Book List</h1>
    <ul>
        <% books.forEach(book=> { %>
            <li>
                <%= book.title %> by <%= book.author %>
            </li>
            <% }); %>
    </ul>
</body>

</html>
Javascript
//app.js

import express from "express";

const app = express();
const port = 3001;

app.set("view engine", "ejs");

app.get("/", (req, res) => {
    const books = [
        { title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
        { title: "To Kill a Mockingbird", author: "Harper Lee" },
        { title: "1984", author: "George Orwell" },
    ];

    res.render("index", { books });
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Output:

Screenshot-(764)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads