Caching images in the public folder

What is the best way to allowing caching of images in the public folder?

I saw in the documentation that next.js can’t cache assets in the public folder because they may change. But is there a way to override this? I’ve been trying to mess with the headers in the vercel.json configuration, but to no avail.

Expected behavior:
When requesting a svg or png from an external site, it will be cached for further uses.
Header: Cache-Control: public, max-age=3600, immutable

Actually behavior:
The image must be fetched everytime
Header: Cache-Control: public, max-age=0, must-revalidate

Tried using the following configuration in vercel.json:

{
	"github": {
		"silent": true
	},
	"headers": [
		{
			"source": "/(.*)\\.(png|jpg|jpeg|gif|webp|svg|ico)$",
			"headers": [
				{
					"key": "Cache-Control",
					"value": "public, max-age=3600, immutable"
				}
			]
		}
	]
}

Hi @spencer-highlightio, welcome to the Vercel Community!

I was able to use vercel.json configuration to cache a /public/vercel.png file:


{
  "headers": [
    {
      "source": "/(.*).png",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "public, max-age=3600"
        }
      ]
    }
  ]
}

I hope this was helpful.

2 Likes

Thanks, @anshumanb. We ended up moving the assets into the other project as they were no longer needed in the project hosted in Vercel.

1 Like