Nearby lessons

5 of 14

🧩 How to Render JSON and HTML in Express JS

πŸ“Œ What is Response Rendering?

πŸ’‘ Understanding Response Rendering in Express.js

Express allows us to send different types of responses to the client β€” including HTML and JSON data. Using the res.send() method, we can easily render both.

This feature is useful for building APIs (sending JSON) or creating simple web pages (sending HTML).

🧱 Step 1: Rendering HTML in Express

We can directly send HTML code inside the res.send() method. Express automatically sets the Content-Type header to text/html.

Let's look at an example that displays an HTML response with links between two routes (/ and /about).

Express.js Server
NODE RUNTIME
var express = require('express');
var app = express();

app.get('/', (req, res) => {
    res.send(`
        <h1>Welcome To CodingsPoints</h1>
        <a href='/about'>Go to About Page</a>
    `);
});

app.get('/about', (req, res) => {
    res.send(`
        <h1>Welcome To About Page</h1>
        <a href='/'>Go to Home Page</a>
    `);
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

βš™οΈ Explanation: Rendering HTML

  • res.send() β€” Sends an HTML response to the client.
  • You can include <h1>, <a>, or any HTML tag.
  • Express automatically sets Content-Type as text/html when sending HTML strings.
  • Useful for sending quick HTML-based responses for small apps or testing routes.

πŸ“¦ Step 2: Rendering JSON in Express

Express can also send JSON data directly using the same res.send() method. If you pass an object or array, Express automatically sets Content-Type to application/json.

Let’s explore examples for both single and multiple JSON objects.

Express.js Server
NODE RUNTIME
var express = require('express');
var app = express();

app.get('/', (req, res) => {
    res.send({
        name: "Codings Points",
        year: 2025
    });
});

app.get('/about', (req, res) => {
    // Array of objects
    res.send([
        { name: "Codings", year: 2025 },
        { name: "Points", year: 2026 },
        { name: "Codings Points", year: 2027 }
    ]);
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

πŸ“˜ Explanation: Rendering JSON

  • res.send(object) β€” Sends a JSON response automatically.
  • res.send(array) β€” Sends an array of JSON objects.
  • Express detects the data type and sets Content-Type to application/json.
  • Ideal for building RESTful APIs that return structured data.

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Serve Static Files