Express.Static In Depth: How to simplify your web server by serving static content with Express built in middleware

Serving individual routes to static files with node can be a pain, so if you aren’t already, here’s how to use the Express.static middleware to automatically serve static web content.

Middleware are functions which act on all requests passed through their routes. They are specified on an express server with the serverName.use(someMiddleware) function. Middleware all share the same function signature:

Notice the last argument, this next parameter represents a function passed into all middleware, and is used to proceed the Request and Response cycle. Request and Response objects will be passed through the middleware, and the route will not proceed until the next function is called. Correctly chaining middleware is the secret to clean express server code, if you can abstract some functionality to a middleware function, you should.

Good targets for middleware abstraction are: common tasks needed for all routes, authentication steps before reaching the end of a route, asynchronous processes that must be completed before a following middleware or end of route (hint: call next in the callback), or for serving static content.

The setup is easy:

That’s it! The serve static middleware is now initiated. All routes that request a static html, css, js, or json file will be served automatically from the specified directory. It’s that easy.

Using express to serve static content to different routes

Express.static can be implemented multiple times to serve different routes. This is super helpful if you have multiple versions of static content with the same name. Now, requests to ‘/login’ will be served the index.html file in login, and requests to ‘/main’ will be served the index.html file in the other directory.

Where a middleware is specified matters, all requests will route through it if the middleware is specified above the route:

If a index.html file is within the public directory, it will get served before reaching this get route. Be careful where you specify it, or use these nifty options to get the exact behavior you want:

Go deeper with express.static configuration options

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.