How to add the Cache-Control header in Remix

Adding Cache-Control via the headers function

You can add the Cache-Control header to your response by exporting a headers function from your route file. This function should return an object with the header names as keys and the header values as values.

export const headers = () => ({
  "Cache-Control": "no-transform, max-age=3600, s-maxage=7200",
})
This will only add the Cache-Control header to the response for this route. If you want to add the Cache-Control header to all responses, you can export a headers function from your root file:
// in app/root.tsxexport const headers = () => ({
  "Cache-Control": "no-transform, max-age=3600, s-maxage=7200",
})
Then, in any particular route file, you can override the headers by exporting a headers function from that file, which will take precedence over the root headers function.

Adding Cache-Control via loader response

You can also add the Cache-Control header to a route by returning headers along with the response from your loader function. To do this, we need to return a Response object from the loader function. and specify the headers option with a record of the HTTP headers we want to send.

export const loader = () => {
  const data = { message: 'Hello, world!' }

  return new Response(JSON.stringify(data), {
    headers: {
      "Cache-Control": "no-transform, max-age=3600, s-maxage=7200",
    },
  })
}