req.fresh Property in Express.js


The req.fresh property returns True or false based upon the status of the client's cache. If the cache is still fresh, True is returned, else False will be returned to indicate that the cache is stale and all the content needs to be sent instead of just non-cached part.

When a client sends the Cache-Control as no-cache request header to indicate an end-to-end reload request, False will be returned to make the handling of these requests transparent.

Syntax

req.fresh

Example 1

Create a file with the name "reqFresh.js" and copy the following code snippet. After creating the file, use the command "node reqFresh.js" to run this code as shown in the example below −

// req.fresh Property Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining Multiple routings
app.get('/api', function (req, res) {
   console.log(req.fresh);
   res.send();
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request − http://localhost:3000/api

Output

C:\home
ode>> node reqFresh.js Server listening on PORT 3000 false

Example 2

Let's take a look at one more example.

// req.fresh Property Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining Multiple routings
app.get('/api', function (req, res) {
   console.log("When Cache-control is no-cache", req.fresh);
   res.send();
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET Request − http://localhost:3000/api

Output

C:\home
ode>> node reqFresh.js Server listening on PORT 3000 When Cache-control is no-cache false

Updated on: 29-Jan-2022

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements