Atharva
Atharva

Reputation: 6969

How to apply max-age in cache control for images in Nextjs?

I have created the following next.config.js file:

/** @type {import('next').NextConfig} */

const nextConfig = {
    
    async headers() {
        return [
            {
                source: "/_next/image",
                headers: [
                    {
                        key: "Cache-Control",
                        value: "public, max-age=86400, immutable", // 86400 seconds = 1 day
                    },
                ],
            },
        ];
    },
};
module.exports = nextConfig;

I am using GCP load balancer for Cloud Run Service that hosts this application with Cloud CDN enabled. There also I have set the TTL value for client, default and max to 1 day. I am still getting the Cache-Control header for images set as public,max-age=60,must-revalidate in response headers in website live in production.

Can you please suggest what else might need to be changed?

Upvotes: 0

Views: 396

Answers (1)

Qavi Nizamani
Qavi Nizamani

Reputation: 11

You can configure minimumCacheTTL to increase the cache duration when the upstream image does not include Cache-Control header or the value is very low.

module.exports = {
  images: {
    minimumCacheTTL: 15552000, // 6 months
  },
}

Note: If you need to change the caching behavior per image, you can configure headers to set the Cache-Control header on the upstream image (e.g. /some-asset.jpg, not /_next/image itself).

Therefore to set cache for all of the images you need to configure minimumCacheTTL value.

Upvotes: 1

Related Questions