Express Render HTML

Aug 26, 2020

Express makes it easy to render plain HTML, either from a JavaScript string or from a file. Given an HTML string, all you need to do is call res.send(), Express takes care of setting the content-type header for you:

const html = '<h1>Hello, World!</h1>';

const express = require('express');

const app = express();
app.get('*', (req, res) => {
  // That's all you need to do! If you pass a string to `res.send()`,
  // Express sets the response-type header to `text/html`
  res.send(html);
});

const server = await app.listen(3000);

// Example of using the server
const axios = require('axios');

const res = await axios.get('http://localhost:3000');
res.headers['content-type']; // 'text/html; charset=utf-8'
res.data; // '<h1>Hello, World!</h1>'

From a File

If your HTML is in a file test.html, rather than a string, you can use Express' sendFile() function. The only caveat is that you must specify the absolute path to test.html.

app.get('*', (req, res) => {
  // `__dirname` contains the directory that this code is in.
  res.sendFile(`${__dirname}/test.html`);
});

Built an Express app and want to deploy it?

We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.

Deploy your Express app on Railway in minutes

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials