Express express.static() Function (original) (raw)

Last Updated : 5 Aug, 2025

In Express.js, serving static files like images, CSS, and JavaScript used to require custom routes. With the express.static() function, you can serve static content directly from a folder, making it easier and faster. Let's explore how this function works and how you can use it in your web applications.

What is express.static()?

The express.static() is a built-in middleware function in Express.js that allows you to serve static files (like images, HTML, CSS, and JavaScript) directly to the client. It automatically makes all files inside a specified folder accessible via HTTP requests. You don’t have to create custom routes for each file.

**Syntax

app.use(express.static('directory_name'));

Code implementation of express.static()

Step 1: Create a public Folder

First, create a folder named public in your project directory. Inside this folder, place an index.html file and any images you want to display.

Screenshot-2025-03-05-170957

public folder

Step 2: Make a server.js file

Make a server.js file that contains the code logic to send the image to the specified route on to your localhost route

JavaScript ``

//server.js const express = require('express'); const app = express();

// Use express.static middleware to serve static files from the "public" folder app.use(express.static('public'));

// Define a route (this is optional) app.get('/', (req, res) => { res.send('Welcome to my static website!'); });

// Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(Server is running on port ${PORT}); });

``

Step 3: Run the server

Use the following command to run the server.js file in your current working directory of the project

node server.js

Step 4: Open Your Browser

Visit the localhost:3000 to see the image that has been rendered on the page

Screenshot-2025-03-05-170816

How the express.static() works?

What is the use of express.static() function?

Advantages of express.static() function

Conclusion

The express.static() function makes serving static files in your Express app much easier. Instead of writing custom routes for each file, you simply specify a directory, and Express handles the rest. It improves performance with caching, simplifies routing, and automatically serves files with the correct content type.