Search code examples
javascriptnode.jscaching

Why req.fresh always return false


I am trying to work with cache but every time I am getting false for req.fresh. On server side I am using Node.js.

Ref. link - https://expressjs.com/en/5x/api.html#req.fresh

Below is my Node.js code

const express = require("express");
const app = express()
const cookieParser = require('cookie-parser');
const PORT = 4040
const v1Api = express.Router()



v1Api.get('/:apple', (req, res) => {
    console.log("is req fresh %s", req.fresh);
    const parms = {
        myVar: req.params.apple,
        baseUrl: req.baseUrl,
        cookies: req.cookies
    };

    res.json(parms)
})

app.use(['/api/v1','/apiz/v1'], v1Api)
app.use(cookieParser);

-- I just want to test this with true result, so that can work further on this.

On the client end I am using Postman, below is the screenshot of the same. (please check header)

enter image description here


Solution

  • Under the hood, express uses fresh, which uses ETag from the response, and If-None-Match from request Headers, if the value of both fields matches it breaks the script and sends a blank response with status code 304, which means there is no new data for it.

    If these 2 values don't match it will return false, then we can execute our script and send the value which shall be used next time the application sends a request to the server.

    FYI - The value for ETag can be a timestamp or any other value which you use to validate the requested content, and it only works with GET and HEAD methods.

    Working Example -

    const app = require('express')();
    require('dotenv').config()
    const port = process.env.PORT || 4500;
    
    app.get("/api/v1/cache-check", (req, res) => {
    
        // Get value for ETag where you saved it initially, In general, you 
        // may use a file to store timestamps with API request name
    
        res.set('ETag', "foo")
        res.send({
            'fresh': req.fresh,
        });
    });
    
    app.listen(port);