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`);
});

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

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

More Express Tutorials