July 3, 2024

express.static() in Express.js

In every web application we do have static content such as images, CSS files, and JavaScript files that has to be rendered. In Express.js you can use the express.static built-in middleware function to serve such static files.

express.static syntax

express.static(root, [options])
  • root- This argument specifies the root directory from which to serve static assets.
  • options- You can get more information about options argument here.

For example-

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

By providing the above middleware function, static files are served by combining root URL with the provided root directory. Static files are accessed using path relative to PROJECT_ROOT_DIR/public, you don't need to provide the absolute path of each static asset. This makes it convenient to access such static files and avoids hardcoding absolute paths.

express.static example

Suppose you have a public directory with in your project root directory and with in public you have sub-directories css and images. With in these sub-directories, you have few stylesheets and images respectively.

express.static() in Express.js

In order to serve these static assets you can set the public directory using the express.static() middleware.

app.js

const express = require('express');
const app = express();
const port = 3000;
const path = require('path');

// To serve static files like CSS
app.use(express.static(path.join(__dirname, 'public')));

// view engine setup
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('user');
})

Since the route setup here renders user.ejs when root URL is accessed so let's create a user.ejs file.

views\user.ejs

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>User Page</title>
        <link rel="stylesheet" href="/css/style.css">
        <link rel="stylesheet" href="/css/user.css">
    </head>
    <body> 
        <h2>User Data</h2>
        <table>
            <tr> 
                <td>Reene</td>
                <td>28</td>
                <td>F</td>
            </tr>
            <tr> 
                <td>Badal</td>
                <td>34</td>
                <td>M</td>
            </tr>
        </table>
        <img src="/images/testimage.png" />
    </body>
</html>

As you can see the path to style.css here is given as "/css/style.css". As per my project structure css directory resides in "/myexpressapp/public/css" but the path to css in ejs file is relative to public directory which is possible because of setting it using express.static.

Same way for image, path used is "/images/testimage.png"

That's all for the topic express.static() in Express.js. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment