Configuring static directories in Express JS and EJS


Configuring static directories in Express.js is essential for serving static assets such as CSS, JavaScript, and images to your clients. Express.js uses the express.static middleware to serve these files. Here’s how you can configure and manage static directories in Express.js when using EJS as the templating engine:

1. Basic Setup

  1. Create a Directory for Static Files

    Create a directory in your project to hold your static files. A common name for this directory is public.

    project-directory/ ├── public/ │ ├── css/ │ ├── js/ │ └── images/ ├── views/ └── app.js
  2. Configure Express to Use the Static Directory

    In your main Express application file (e.g., app.js or server.js), configure Express to serve static files from the public directory:

    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'))); // Set the view engine to EJS app.set('view engine', 'ejs'); // Example route app.get('/', (req, res) => { res.render('index'); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });

    The express.static middleware will serve files from the public directory. For example, a file located at public/css/style.css would be accessible at /css/style.css.

2. Serving Static Files from Multiple Directories

If you need to serve static files from multiple directories or with different routes, you can use express.static multiple times with different paths:

app.use('/static', express.static(path.join(__dirname, 'public'))); app.use('/assets', express.static(path.join(__dirname, 'assets')));

In this configuration:

  • Files in public will be served under the /static route (e.g., public/css/style.css would be accessible at /static/css/style.css).
  • Files in assets will be served under the /assets route (e.g., assets/js/script.js would be accessible at /assets/js/script.js).

3. Using Static Files in EJS Templates

In your EJS templates, you reference static files relative to the routes configured:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Page</title> <link rel="stylesheet" href="/css/style.css"> </head> <body> <h1>Hello, World!</h1> <img src="/images/logo.png" alt="Logo"> <script src="/js/script.js"></script> </body> </html>

4. Customizing Static File Routes

You can also customize the routes from which static files are served. For example, you might want to serve static files from a different URL path:

app.use('/public', express.static(path.join(__dirname, 'public')));

In this case, files in the public directory will be accessible under the /public route (e.g., public/css/style.css would be available at /public/css/style.css).

5. Serving Static Files with Caching

For better performance, you can configure caching for static files. Express’s express.static middleware supports caching through its maxAge option:

app.use(express.static(path.join(__dirname, 'public'), { maxAge: '1d' // Cache static files for 1 day }));

6. Handling Static Files in Production

For production, ensure that:

  • Static files are optimized (e.g., minified CSS/JS, optimized images).
  • You may use build tools or bundlers like Webpack or Gulp to handle and optimize static assets.
  • Consider using a content delivery network (CDN) to serve static files efficiently and reduce server load.

Summary

  1. Create Static Directory: Place your static files in a directory like public.
  2. Configure Middleware: Use express.static to serve files from the static directory.
  3. Multiple Directories: Use multiple express.static middleware calls to serve from different directories or routes.
  4. Reference Files in EJS: Include static files in EJS templates using relative paths.
  5. Custom Routes: Customize the URL paths for serving static files if needed.
  6. Caching: Configure caching to improve performance.
  7. Production: Optimize and manage static files for production environments.