Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable caching for download method of Loopback Storage Component?

I'm using Loopback as an backend API, and also using Storage component as an CDN to upload and download image and sound file for my website. My website using a lot of image from that. But all the image files is not cach-enable.

I want to enable cache by adding a "Cache-Control:max-age=2678400" header to the file but don't know how to do it. Can someone help me or suggest any better solution. I really appreciate it.

Thank you!

like image 766
imrhung Avatar asked Dec 13 '25 02:12

imrhung


1 Answers

Finally I have found a workaround using Middleware. Create a middleware in server/middleware folder:

// cache.js
module.exports = function () {

    return function cacheImages(req, res, next) {

        // Check if download file:
        if (req.originalUrl.includes('/api/files/') && req.originalUrl.includes('/download/')) {
            console.log("Here at the middle ware");

            console.log(req.originalUrl);

            res.set('Cache-Control', 'max-age=315360000');
        }

        next();
    }
}

and add this middleware in server/middleware.json config file:

...
"initial": {
    "./middleware/cache": {}
}
...

Hope this help! :)

like image 127
imrhung Avatar answered Dec 16 '25 11:12

imrhung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!