Open In App

How to set response header on Express JS assets?

In Express.js applications, we can set the response headers on assets to improve performance and also control the cache behavior.

In this article, we will set the response header on Express.js assets by using 2 different approaches. We will see the practical implementation of this approach in terms of examples and output.



The following approaches will be used to set response header in Express

Prerequisites

Steps to create Express application

Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal.

mkdir folder-name
cd folder-name

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.

npm init -y

Step 3: Now, we will install the express dependency for our project using the below command.

npm i express

Step 4: Now create the below Project Structure of our project which includes the file as app.js and public directory in which images are stored.

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2"
}

Approach 1: Using Middleware

Example: Below is the implementation of the above-discussed approach.




//app.js
 
const express = require("express");
const app = express();
// middleware to set response headers for assets
app.use("/assets", (req, res, next) => {
    // setting the response headers
    res.setHeader("Cache-Control", "public, max-age=3600");
    // cache control header
    // next middleware or route handler
    next();
});
// serving static assets from the 'public' directory
app.use("/assets", express.static("public"));
// route handler
app.get("/", (req, res) => {
    res.send("Hello GeeksforGeeks!");
});
// start the server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Output:

Approach 2: Using Route Handler Directly

Example: Below is the implementation of the above-discussed approach.




//app.js
 
const express = require("express");
const app = express();
// servingstatic assets with response headers directly in the route handler
app.get("/assets/:filename", (req, res) => {
    const filename = req.params.filename;
    // response headers
     
    // cache control header
    res.setHeader("Cache-Control", "public");
     
    // expires header (1 hour from now)
    res.setHeader("Expires", new Date(Date.now() + 3600000).toUTCString());
     
    // sending the asset with the response headers
    res.sendFile(filename, { root: "public" });
});
// route handler
app.get("/", (req, res) => {
    res.send("Hello World!");
});
// starting the server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Output:


Article Tags :