0
0
ExpressHow-ToBeginner · 3 min read

How to Set Static Folder in Express: Simple Guide

In Express, you set a static folder by using the express.static middleware and passing the folder path to it. For example, app.use(express.static('public')) serves files from the public folder as static assets.
📐

Syntax

The basic syntax to set a static folder in Express is:

app.use(express.static('folder_name'))

Here:

  • app.use() adds middleware to your Express app.
  • express.static() is a built-in middleware function to serve static files.
  • 'folder_name' is the folder where your static files like images, CSS, or JavaScript are stored.
javascript
app.use(express.static('public'))
💻

Example

This example shows how to serve static files from a folder named public. When you visit http://localhost:3000/image.png, Express will look for image.png inside the public folder and serve it.

javascript
import express from 'express';
const app = express();
const port = 3000;

// Set 'public' folder as static
app.use(express.static('public'));

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Output
Server running at http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when setting static folders include:

  • Not specifying the correct folder path, causing files not to be found.
  • Placing express.static middleware after routes that handle the same paths, so static files are never served.
  • Forgetting to create the static folder or missing files inside it.

Always ensure the folder exists and express.static is used before other route handlers.

javascript
/* Wrong: static middleware after routes */
app.get('/image.png', (req, res) => {
  res.send('This will block static file serving');
});
app.use(express.static('public'));

/* Right: static middleware before routes */
app.use(express.static('public'));
app.get('/image.png', (req, res) => {
  res.send('This route will not block static files');
});
📊

Quick Reference

Tips for setting static folders in Express:

  • Use express.static middleware to serve static files.
  • Place the middleware near the top of your middleware stack.
  • Use relative or absolute paths to your static folder.
  • Static files are served relative to the folder you specify.
  • You can serve multiple static folders by calling app.use multiple times.

Key Takeaways

Use app.use(express.static('folder')) to serve static files in Express.
Place the static middleware before other routes to avoid blocking static file serving.
Ensure the static folder exists and contains the files you want to serve.
You can serve multiple static folders by adding multiple express.static middlewares.
Static files are accessed by their path relative to the static folder.