Support Forums

Netlify cache headers

Hello netlify team!
I want to ask your about caching. I’ve tried several approaches and it seems to me that caching on netlify doesn’t work with api routes from Next.js. My goal is to cache response from api route. So I have route like this: /api/something

  1. I’ve tried to set Cache control headers as it is advised in Next.js docs. Like this:
          `public, s-maxage=180, stale-while-revalidate`

And it has a very strange behaviour, because I had 2 duplicate Cache control headers in response like this and cache didn’t work:

  1. Then I found that I could write headers in netlify.toml. I deleted my headers in next.js api routes and set headers in netlify.toml like this:
  for = "/api/something/*"
    Cache-Control = "public, max-age=3600"

With this approach I had only one Cache control header and it was: Cache control: no-cache.
Also I tried to give this header to my assets like this:

  for = "/*.css"
    Cache-Control = "public, max-age=259200"

And it worked!

So is there any way to cache my api routes?

Nextjs API routes are generated by Netlify Functions and Netlify Functions are not static files, so _headers do not work on those. Functions control their own headers.

About how to get it working with Nextjs, I’ll confirm with devs and revert.

@hrishikesh oh, I see. If there is any way to achieve it, it will be perfect. Thanks.

@hrishikesh Hello! Is there any news about cache on api routes?

We’ve a pairing with the developers in about 4 to 5 hours from now. We will confirm during that and let you know.

Hey @alisakova,

We talked with the team and have a rather bad news for you. Sending custom caching responses from functions is rather buggy and not supported and down the line, we’re considering deprecating it as it leads to more problems than it solves.

You might want to use On Demand Builders to keep the content “cached” by the CDN, but you can’t control cache headers sent to the browsers.