- ExpressJS - Home
- ExpressJS - Overview
- ExpressJS - Environment
- ExpressJS - Installation
- ExpressJS - Hello World
- ExpressJS - Routing
- ExpressJS - HTTP Methods
- ExpressJS - URL Building
- ExpressJS - Middleware
- ExpressJS - Templating
- ExpressJS - Static Files
- ExpressJS - Form Data
- ExpressJS - Database
- ExpressJS - Cookies
- ExpressJS - Sessions
- ExpressJS - Authentication
- ExpressJS - RESTful APIs
- ExpressJS - Scaffolding
- ExpressJS - Serving Dynamic Content
- ExpressJS - Handling File Uploads
- ExpressJS - Internationalization(i18n)
- ExpressJS - Security Practices
- ExpressJS - Rate Limiting
- ExpressJS - Slowing Down Responses
- ExpressJS - Error handling
- ExpressJS - Debugging
- ExpressJS - Best Practices
- ExpressJS - Resources
ExpressJS - Serving Static Files
Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware.
app.use(express.static('public'));
Note − Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.
Note that the root route is now set to your public dir, so all static files you load will be considering public as root. To test that this is working fine, add any image file in your new public dir and change its name to "testimage.jpg". In your views, create a new view and include this file like −
static_files.pug
html head body h3 Testing static file serving: img(src = "/testimage.jpg", alt = "Testing Image")
index.js
var express = require('express'); var app = express(); app.use(express.static('public')); app.set('view engine', 'pug'); app.set('views','./views'); app.get('/static_files', function(req, res){ res.render('static_files'); }); app.listen(3000);
You should get the following output −

Multiple Static Directories
We can also set multiple static assets directories using the following program −
index.js
var express = require('express'); var app = express(); app.use(express.static('public')); app.use(express.static('images')); app.listen(3000);
Virtual Path Prefix
We can also provide a path prefix for serving static files. For example, if you want to provide a path prefix like '/static', you need to include the following code in your index.js file −
index.js
var express = require('express'); var app = express(); app.use('/static', express.static('public')); app.listen(3000);
Now whenever you need to include a file, for example, a script file called main.js residing in your public directory, use the following script tag −
<script src = "/static/main.js" />
This technique can come in handy when providing multiple directories as static files. These prefixes can help distinguish between multiple directories.