How to serve static files with Express

In many instances you required to server static assets such as images, css files and JavaScript files, so today we gonna show you, how you can server static files using express framework.

For example, If you have following directories under the public directory
css – which holds the css files
js – which holds the js files
images -which holds the images.

By default, Express does not allow you to serve static files. You need to enable it using the built-in express.static() middleware function.

Let’s serve static files of public directory

Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.

It means you can access assets something like below shown URLs.

See above URLs public is not part of the url; public directory act as the root directory.

Multiple Static Directories

We can also set multiple static assets directories, by calling the express.static middleware function multiple times.

Virtual Path Prefix

You can also provide a path prefix for serving static files. For example, if you want to provide a path prefix like ‘/static’, you need use the static middleware as shown below.

Now, you can load the files that are in the public directory from the /static path prefix.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.