How to useRoute Handler Directly in Express

  • In this approach, we are directly setting the response header in the router handler for the assets.
  • We have set the 2 different headers Cache-Control” to ‘public‘ and “Expires” to indicate the asset’s expiration time (1 hour from now).

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

Javascript




//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:



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

Table of Content

  • Using Middleware
  • Using Route Handler Directly

Similar Reads

Prerequisites

Node JS Express JS...

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....

Approach 1: Using Middleware

In this approach, we have defined the middleware before serving the static assets. When the request to the asset is done, it will go through the middleware in which we have set the response headers. In the below example, we have set the response header as “public, max-age=3600“, which specified the cache policy allowing the public caching for up to 3600 seconds....

Approach 2: Using Route Handler Directly

...