Serve Static Files with Express

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet
Published 7 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.

egghead
egghead
~ 7 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today