Static Files in ExpressJS
Expert-led Online Courses: Elevate Your Skills, Get ready for Future - Enroll Now!
When building a web application using Express.js, serving static files such as images, stylesheets, and client-side JavaScript is an essential aspect. Express.js provides a built-in middleware called express.static that makes it easy to serve static files from a directory on the server.
What is the express.static Middleware?
The express.static middleware is a function that takes a directory path as an argument and returns a middleware function. This middleware function serves static files from the specified directory when a request is made to the server.
Here’s an example of using express.static to serve static files from a directory called public in the root of the application:
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
Explanation
In this example, the express.static middleware is applied using the app.use method. The middleware serves files from the public directory by default when a request is made to the server.
Configuring the express.static Middleware
The express.static middleware can be customized with various configuration options. Here are some of the most commonly used options:
1. dotfiles: Determines how dotfiles (files that start with a dot) are treated. Acceptable values are ‘allow’ (to serve them), ‘deny’ (to deny them), and ‘ignore’ (to treat them as normal files). The default value is ‘ignore’.
2. etag: Enables or disables the use of ETags (entity tags) for cache validation. The default value is true.
3. extensions: An array of file extensions to serve without a file extension in the URL. For example, if ‘html’ is included, a request to /about will serve /about.html if it exists. The default value is false.
4. fallthrough: Determines whether to continue to the next middleware function if a file is not found. The default value is true.
5. immutable: Enables or disables the use of the immutable directive in the Cache-Control header. The immutable directive indicates that the file is unlikely to change over time and can be cached indefinitely by the browser. The default value is false.
6. index: A boolean value or a string specifying the file to serve when a directory is requested. The default value is true, which serves the file index.html.
7. lastModified: Enables or disables the use of the Last-Modified header for cache validation. The default value is true.
8. maxAge: Specifies the maximum age (in milliseconds) of the cache for static files. The default value is 0, which disables caching.
9. redirect: Enables or disables redirecting to a trailing slash when a directory is requested. The default value is true.
10. setHeaders: A function that allows custom headers to be set on the response. The function takes two arguments: the response object and the file path being served.
Here’s an example of using express.static with some of these options:
const express = require('express');
const app = express();
app.use(express.static('public', {
dotfiles: 'ignore',
etag: false,
extensions: ['html', 'css', 'js'],
index: 'index.html',
maxAge: '1d',
redirect: true,
setHeaders: (res, path, stat) => {
res.set('Cache-Control', 'public, max-age=86400');
}
}));
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
Explanation
In this example, we’re serving static files from the `public` directory, ignoring dotfiles, disabling ETags, serving HTML, CSS, and JavaScript files without extensions in the URL, setting the `index.html` file as the default for directories, caching files for one day (`’1d’`), redirecting to a trailing slash when a directory is requested, and setting the `Cache-Control` header to indicate that the file can be cached for one day.
Serving Static Files from Multiple Directories
In some cases, you may need to serve static files from multiple directories in an Express.js application. For example, you might want to serve files from a `public` directory for client-side assets and a `uploads` directory for uploaded files.
You can use `express.static` multiple times with different directory paths to serve static files from multiple directories. Here’s an example:
const express = require('express');
const app = express();
app.use(express.static('public'));
app.use('/uploads', express.static('uploads'));
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
In this example, we’re serving files from the public directory by default and serving files from the uploads directory at the /uploads route.
Conclusion
The express.static middleware is a powerful and flexible tool for serving static files in an Express.js application. By understanding its configuration options and usage patterns, you can efficiently serve static assets in your web applications. Whether you’re building a small personal project or a large-scale web application, express.static is a valuable tool to have in your toolkit.
Did you like this article? If Yes, please give DataFlair 5 Stars on Google

