0
0
ExpressHow-ToBeginner · 3 min read

How to Use Virtual Path Prefix for Static Files in Express

In Express, you can use a virtual path prefix for static files by passing a mount path as the first argument to app.use() and express.static() as the second. This prefix acts like a folder name in the URL but does not affect the actual file system path.
📐

Syntax

The syntax to serve static files with a virtual path prefix in Express is:

app.use('/virtual-prefix', express.static('folder-path'))

Here:

  • /virtual-prefix is the URL path prefix clients will use.
  • express.static('folder-path') serves files from the actual folder on your server.
javascript
app.use('/virtual-prefix', express.static('public'))
💻

Example

This example shows how to serve static files from the public folder under the URL path /static. So a file public/image.png is accessible at http://localhost:3000/static/image.png.

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

// Serve static files with virtual path prefix '/static'
app.use('/static', 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 using virtual path prefixes for static files include:

  • Not matching the URL prefix in the browser request with the prefix in app.use().
  • Using the prefix as a real folder name on disk instead of a virtual URL path.
  • Placing express.static middleware after routes that block requests.

Example of a wrong and right way:

javascript
// Wrong: No virtual prefix, but URL uses one
app.use(express.static('public'));
// Browser requests '/static/image.png' will 404

// Right: Use virtual prefix matching URL
app.use('/static', express.static('public'));
📊

Quick Reference

  • Use app.use('/prefix', express.static('folder')) to add a virtual path prefix.
  • The prefix appears in the URL but not in the file system.
  • Ensure client URLs include the prefix to access files.
  • Order middleware properly to avoid blocking static files.

Key Takeaways

Use app.use('/prefix', express.static('folder')) to serve static files with a virtual URL prefix.
The virtual prefix is part of the URL path, not the actual folder structure.
Ensure client requests include the prefix to access static files correctly.
Place static middleware before other routes that might block requests.
Mismatch between URL and prefix causes 404 errors for static files.