How to useMiddleware in Express
- 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.
Example: Below is the implementation of the above-discussed approach.
Javascript
//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 w3wiki!" ); }); // start 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
Contact Us