How To Serve Static Files in Express
Static files are files that are served directly to the browser without any server-side processing: HTML, CSS, JavaScript, images, and fonts. Express has a built-in middleware function called express.static that handles this.
express.static
app.use(express.static('public'));
This tells Express to serve any file inside the public/ folder. A request to /style.css will return public/style.css.
Using path.join(__dirname, 'public') is safer than a bare string because it builds an absolute path that works regardless of where Node is started from:
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
Step-by-step example
Set up the project
mkdir my-project
cd my-project
npm init -y
npm install express
Create the main app file:
touch index.js
Add static files
Create a public folder with some files:
my-project/
index.js
public/
index.html
style.css
hello.png
Create the Express server
const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));
Start the server:
node index.js
Now:
http://localhost:3000/index.htmlservespublic/index.htmlhttp://localhost:3000/style.cssservespublic/style.csshttp://localhost:3000/hello.pngservespublic/hello.png
Any file you add to public/ becomes available at the matching URL path.
What to read next
- Middleware
: how
express.staticfits into the middleware chain - Creating an Express App : the full server structure