Serve Static Files with Express

Mark Shust
InstructorMark Shust

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 5 years ago

In this lesson we will find out how to serve static assets (images, css, stylesheets, etc.) with Express. We will go over writing initial boilerplate for a simple Express app, and using Express's built-in middleware to serve these assets through a web server on Node.js.

Let's set up an Express app that serves up a simple request of an image of our cat friend. We'll first require the path module to do path lookups, and then require Express, our web server. Then we'll create an instance of Express.

Let's define a route at the root of our address to serve up requests. We will call this on method on the response object with some simple HTML that sends back a header with an image of our cat friend.

To serve up images, we'll need to use the built-in middleware for serving up static assets in Express. First, we call app.use, followed by the path to reply the middleware on, in this case, /images. Then we will call the Express static middleware with the path location where our static assets will be stored.

By defining the absolute path with __dirname, we can run Express from any directory, and not worry about being in the relative path. We'll store our images in a folder at public/images. Finally, we will listen for requests on port 8080.

Let's make our public/images directory, then copy our herman.jpg image to it. Now we'll install Express with yarn add express.

Then we will start our web server with Nodeindex.js. Let's check our web browser to see our friend, Herman, being properly served up with Express.