To start serving files, pass the name of the directory that contains the static assets to the express.static middleware.
For example, if you have a folder named public at the root of your project:
import express from'express';
const app = express();
// Serve static files from the 'public' directory
app.use(express.static('public'));
app.listen(3000, ()=> {
console.log('Server is running on port 3000');
});
Now, you can load the files that are in the public directory:
http://localhost:3000/images/logo.png
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
[!NOTE]
Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.
2. Using an Absolute Path
The path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the Express app from another directory, it is safer to use the absolute path of the directory you want to serve:
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by express.static, specify a mount path for the middleware function, as shown below:
// Files will be accessible under the /static prefix
Express looks up the files in the order in which you define the middleware functions.
Best Practices
[!IMPORTANT]
Security: Do not put sensitive files (like configuration files, environment variables, or server code) inside your static directory.
Performance: For production applications, it is highly recommended to use a reverse proxy like Nginx or a Content Delivery Network (CDN) to serve static files instead of relying on Node.js, as they are optimized for static asset delivery.
Caching: Use the maxAge option to leverage browser caching for better performance: