Hi there—in this article I’ll show you how to send an HTML file in response to a request and how to serve static files from your Node server. This continues the previous piece on building a simple server; if you haven’t read that yet, start here:

Previous article: Creating a Simple Node.js Server Using Express

Originally published on Medium in FAUN.dev().

This is how app.js looked at the end of the previous article—nothing fancy: Express is initialized, a server listens on port 9000, and a GET handler on / sends back a message.

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.end('Hi there, Server is working.')
})

app.listen(9000, '127.0.0.1', () => {
  console.log('Server is running on port 9000')
})

Serving a portfolio from /

Say you’ve built a portfolio: an HTML file, CSS, images, and maybe a JS file. We’ll serve that portfolio when someone hits /.

Put index.html in your Node app’s root directory (the project folder that contains package.json). Create a public folder for CSS, JS, images, and any other static assets the markup needs. After that, the folder structure looks something like this—first_node_server is the project folder name:

first_node_server/
├── app.js
├── index.html
├── package.json
└── public/
    ├── css/
    ├── fav/        # favicons
    ├── jquery/     # jQuery scripts used by the portfolio
    ├── images/
    └── svg/

We have the files in place. Next, send index.html when a user visits /.

Sending index.html with res.sendFile

VS Code showing app.js with a GET route that calls res.sendFile for index.html
app.js after switching the `/` handler to res.sendFile.

All of the changes land in the app.get callback. Before, we were sending a string with:

res.end('Hi there, Server is working.')

end is a method on the response object (the second parameter of the route callback). Express also gives us sendFile, which sends a file from the server to the client.

sendFile takes the file path as its first argument. A template string like `${__dirname}/index.html` is the path to the HTML file. You might wonder what __dirname is—we never defined it. Every JS file in Node gets a few predefined variables, and __dirname is one of them. Digging into how Node compiles and runs modules could fill another article; for now, remember that __dirname is the absolute path of the directory containing the current module.

There’s also a reason we use `${__dirname}/index.html` instead of ./index.html. That’s worth its own write-up; until then, this GeeksforGeeks piece covers the difference: Difference between __dirname and ./ in Node.js.

Back to the route: the second argument to sendFile is an error callback that runs after Express tries to send the file. If something goes wrong, we log the error and send the client a message:

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`, (err) => {
    if (err) {
      console.log(err)
      res.end(err.message)
    }
  })
})

Run the app:

node app.js

Then open 127.0.0.1:9000 in the browser.

Browser at 127.0.0.1:9000 showing an unstyled portfolio with broken images
HTML arrives, but styles and images are missing.

You must be thinking, what’s going on? CSS isn’t working, images aren’t working. Open the console and you’ll see errors like the ones below—

Browser DevTools console listing 404s for CSS, jQuery, images, and other static files
Static asset requests failing with 404 before express.static is configured.

For every static file the client requests, the server responded with 404 Not Found. That happens because we still need to tell our Node/Express app where those static files live on disk.

Serving static files with express.static

Add this line before your route handlers (before app.get):

app.use(express.static(`${__dirname}/public`))

Stop the server and start it again with node app.js. That’s important: changing the code won’t show up on a browser refresh alone—you have to restart the process.

Open the browser again at 127.0.0.1:9000.

Styled portfolio homepage at 127.0.0.1:9000 with CSS, plane graphic, and social icons loaded
The same portfolio after static files are served correctly.

Now everything seems to be working—CSS loaded correctly, and images and SVGs are in place. So what magic suddenly happened after adding a single line of code?

app.use(express.static(`${__dirname}/public`))

You can also write:

app.use(express.static('./public'))

Prefer __dirname over ./ so the path stays correct regardless of the working directory you start Node from.

app.use registers middleware—functions that run as part of handling requests. express.static takes the path to the directory that holds your static files. That’s how you tell Express where to look when the browser requests CSS, JS, images, and the rest.

The finished app.js

const express = require('express')
const app = express()

app.use(express.static(`${__dirname}/public`))

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`, (err) => {
    if (err) {
      console.log(err)
      res.end(err.message)
    }
  })
})

app.listen(9000, '127.0.0.1', () => {
  console.log('Server is running on port 9000')
})

That’s sendFile plus static middleware in a nutshell. Thanks for reading—see you next time.