/

Serving Static Assets with Express

Serving Static Assets with Express

In this blog post, we will discuss how to serve static assets directly from a folder in Express. Many web applications have a public subfolder where they store images, CSS files, and more. We will learn how to expose these assets to the root level of the application using Express.

To get started, we need to install Express and require it in our project file:

1
2
const express = require('express');
const app = express();

Next, we can use the express.static middleware to serve our static assets from the public folder:

1
app.use(express.static('public'));

By adding this line of code, Express will be able to serve any file inside the public folder directly to the client. This includes files like images, CSS, JavaScript, and more.

For example, if we have an index.html file inside the public folder, it will be served when the root domain URL (http://localhost:3000) is accessed.

Finally, we need to start our Express server and listen on a specific port. In this case, we will use port 3000:

1
app.listen(3000, () => console.log('Server ready'));

That’s it! Now, if you run your Express application and access the root URL, you should be able to see the assets from the public folder being served.

By following these steps, you can easily serve static assets with Express and enhance the performance and efficiency of your web application.

tags: [“Express”, “static assets”, “web development”]