The Cache-Control response header is the main way to control HTTP caching behavior. You can use the method on your action’s response object to set this header.

The cache_control method accepts one or more of the following as its arguments.

  • :public
  • :private
  • :no_store
  • :must_validate
  • max_age: N (N here and below should be an integer representing a period in seconds)
  • s_maxage: N
  • min_fresh: N

The [Expires response header][mdn-expires] sets the date and time after which the response is considered expired. The Expires header is an older standard, and Cache-Control is preferred by modern browsers.

You can use the #expires method on your action’s response object to set this header along with a matching Cache-Control header.

For example, for a conditional request, there is a two-step workflow:

  1. The response to an initial request includes a “validator” in its headers, either the date of last modification for the resource (a Last-Modified response header and a subsequent If-Modified-Since request header), or an string identifying the version of the resource (an ETag response header and a subsequent If-None-Match request header)
  2. On the next request, the client sends its counterpart request header, and if the server determines the client’s cache is fresh, it can return a 304 Not Modified response allowing the client to use its cached resource

For more detail on conditional requests, see the MDN documentation.

You can use the #fresh method on your action’s response object to set the Last-Modified or ETag validator headers, as well as short circuit action execution when these are included in the request.

Use the #fresh response method with a last_modified_at: option to return a Last-Modified response header and validate a conditional request by its If-Modified-Since header.

  1. The first request to the action (or a request with a stale cache) will see the action handle the request in full before returning its response with a Last-Modified header.
  2. A subsequent request with a matching If-Modified-Since header will receive a 304 Not Modified response, and the action will halt before its processing logic.

For more detail on action halting, see the control flow guide.

ETag

Use the #fresh response method with an option to return an ETag response header and validate a conditional request by its If-None-Match header.

In the below example:

  1. The firsts request to the action (or a request with a stale cache) will see the action handle the request in full before returning its response with an ETag header.
  2. A subsequent request with a matching If-None-Match header will receive a 304 Not Modified response, and the action will halt before its processing logic.

For more detail on action halting, see the control flow guide.