This is a simple static website.
Static files are files that do not change on the server side and are directly served to the client. Examples include HTML files, CSS files, JavaScript files, images, fonts, and other assets. In Express.js, serving static files is straightforward and efficient, allowing you to create a smooth and fast user experience. This chapter will cover everything you need to know about serving static files in Express.js, from the basics to advanced techniques.
Static files are assets that are sent to the client without any server-side processing. They are essential for the frontend of a web application, providing styles, scripts, images, and other resources. Unlike dynamic content, static files remain the same between different requests.
Express.js makes it easy to serve static files using the express.static
middleware. This middleware serves files from a specified directory and handles the file requests from the client.
To serve static files, follow these steps:
express.static
middleware to serve static files.
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Define a route
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, we serve static files from the public
directory. When the client requests a file, such as an image or a CSS file, the server responds with the corresponding file from the public
directory.
Sometimes, you may need to serve static files from multiple directories. You can achieve this by using multiple express.static
middleware instances.
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from 'public' and 'assets' directories
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'assets')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the server serves static files from both the public
and assets
directories. The client can request files from either directory.
You can customize how static files are served by passing options to the express.static
middleware.
const express = require('express');
const path = require('path');
const app = express();
// Custom options for static file serving
const options = {
dotfiles: 'ignore', // Ignore dotfiles like .htaccess
etag: false, // Disable etag generation
index: 'home.html', // Serve 'home.html' as the default file
maxAge: '1d', // Cache static files for one day
};
// Serve static files with custom options
app.use(express.static(path.join(__dirname, 'public'), options));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'home.html'));
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, we customize the static file serving options:
dotfiles: 'ignore'
ensures that dotfiles are ignored.etag: false
disables ETag generation.index: 'home.html'
serves home.html
as the default file.maxAge: '1d'
caches static files for one day.You can use virtual paths to organize your static files more effectively. A virtual path does not map directly to a file system path but acts as a prefix for the static files.
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the 'public' directory with a virtual path
app.use('/static', express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, static files from the public
directory are served with the /static
virtual path. For example, a file located at public/images/logo.png
will be accessible at /static/images/logo.png
.
Caching static files can significantly improve the performance of your web application. By setting cache headers, you can instruct the browser to cache static files for a specified duration.
const express = require('express');
const path = require('path');
const app = express();
// Serve static files with caching
app.use(express.static(path.join(__dirname, 'public'), { maxAge: '1d' }));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the maxAge: '1d'
option sets the cache duration to one day. The browser will cache the static files for 24 hours, reducing the number of requests to the server and improving performance.
When serving static files, it’s essential to consider security to prevent unauthorized access and protect sensitive information.
Avoid Serving Sensitive Files: Ensure that sensitive files like server-side scripts, configuration files, and database files are not served as static files.
Use Appropriate Directory Structure: Organize your static files in a dedicated directory (e.g., public
) and avoid placing sensitive files in the same directory.
Set Appropriate File Permissions: Ensure that only necessary permissions are granted to static files and directories.
Implement Access Control: Use middleware to restrict access to certain static files or directories based on user roles or authentication status.
Let’s build a simple static website that includes HTML, CSS, and JavaScript files.
static-website/
├── node_modules/
├── public/
│ ├── css/
│ │ └── styles.css
│ ├── js/
│ │ └── scripts.js
│ ├── images/
│ │ └── logo.png
│ └── index.html
├── server.js
└── package.json
npm init -y
npm install express
public/index.html:
My Static Website
Welcome to My Static Website
This is a simple static website.
body {
font-family: Arial, sans-serif;
padding: 20px;
}
header {
text-align: center;
margin-bottom: 20px;
}
header img {
width: 100px;
}
main {
text-align: center;
}
button {
padding: 10px 20px;
font-size: 16px;
}
document.getElementById('clickMe').addEventListener('click', () => {
alert('Button clicked!');
});
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
node server.js
http://localhost:3000/
will display the static website.styles.css
.scripts.js
.Serving static files is a fundamental aspect of building web applications with Express.js. By understanding how to serve static files, customize their serving behavior, use virtual paths, implement caching, and consider security, you can create efficient and secure web applications. This chapter provided a comprehensive guide to serving static files, from basic setups to advanced techniques, along with practical examples and best practices. By mastering static file serving, you can enhance the performance and user experience of your Express.js applications. Happy coding !❤️