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