JSON Cache Header on Browser doesn't work

Asked
Active3 hr before
Viewed126 times

9 Answers

cacheheader
90%

Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,The Pragma: no-cache header field is an HTTP/1.0 header intended for use in requests. It is a means for the browser to tell the server and any intermediate caches that it wants a fresh version of the resource, not for the server to tell the browser not to cache the resource. Some user agents do pay attention to this header in responses, but the HTTP/1.1 RFC specifically warns against relying on this behaviour., By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. , Checking the headers is usually done via dev tools which while open will prevent caching from happening unless you force enable caching. – apokryfos Jul 19 '18 at 7:18

I make a request to a php file and I took back these headers

Access - Control - Allow - Origin: *
   Cache - Control: max - age = 360000, must - revalidate
Connection: keep - alive
Content - Type: application / json
Date: Thu, 19 Jul 2018 07: 08: 20 GMT
Expires: Mon, 26 Jul 2040 05: 00: 00 GMT
Pragma: no - cache
Server: nginx
Transfer - Encoding: chunked
load more v
88%

Cache-control is an HTTP header used to specify browser caching policies in both client requests and server responses. Policies include how a resource is cached, where it’s cached and its maximum age before expiring (i.e., time to live).,For example, cache-control: max-age=120 means that the returned resource is valid for 120 seconds, after which the browser has to request a newer version.,The no-cache directive means that a browser may cache a response, but must first submit a validation request to an origin server.,The cache-control header is broken up into directives, the most common of which are detailed below:

The max-age request directive defines, in seconds, the amount of time it takes for a cached copy of a resource to expire. After expiring, a browser must refresh its version of the resource by sending another request to a server.

For example, cache-control: max-age=120 means that the returned resource is valid for 120 seconds, after which the browser has to request a newer version.

cache - control: max - age = 120
load more v
72%

To avoid this, don't send the "Vary" header to IE, and prevent intermediate caches storing it with Cache-Control: max-age=3600, private. Ilya Grigorik covers the server setup for this.,The example above doesn't work in Safari. No matter what you select, it'll fetch the previous response from the cache, meaning it comes back with the wrong content. You ask for JSON, it fetches the JavaScript response from the cache. It's ignoring the "Vary" header in this case, despite getting it right in the "Accept-Language" example.,I assumed the browser would cache both responses independently, but no, the "Vary" header is used for validation, not keying. Here's what the browser does:,It feels like the first entry should be the match because it's more specific, but HTTP caching has no concept of specificity. Having different "Vary" headers for the same URL messes things up.

Loading…
# Request:
   Accept: application / json

# Response
Cache - Control: max - age = 3600
Vary: Accept… some JSON…
# Request:
   Accept: *
/*

# Response
Cache-Control: max-age=3600
…some HTML…
# Request:
   Accept: application / json
# Request:
   Accept: application / json

# Response
Cache - Control: max - age = 3600
Vary: Accept… some newer JSON…
load more v
65%

On the other hand, "private" indicates that the response is intended for a single user only and must not be stored by a shared cache. A private browser cache may store the response in this case.,A cache will send the request to the origin server for validation before releasing a cached copy.,Responses other than GET if something suitable for use as a cache key is defined.,Here is an example of this process with a shared cache proxy:

The cache should not store anything about the client request or server response. A request is sent to the server and a full response is downloaded each and every time.

Cache - Control: no - store

A cache will send the request to the origin server for validation before releasing a cached copy.

Cache - Control: no - cache

On the other hand, "private" indicates that the response is intended for a single user only and must not be stored by a shared cache. A private browser cache may store the response in this case.

Cache - Control: private
Cache - Control: public

For more details, see also the Freshness section below.

Cache - Control: max - age = 31536000

When using the "must-revalidate" directive, the cache must verify the status of stale resources before using them. Expired resources should not be used. For more details, see the Validation section below. See the "Freshness" section below to see what we mean by "stale resources".

Cache - Control: must - revalidate
load more v
75%

HTTP caching is a universally adopted specification across all modern web browsers, making its implementation in web applications simple. Appropriate use of these standards can benefit your application greatly, improving response times and reducing server load. However, incorrect caching can cause users to see out-of-date content and hard to debug issues. This article discusses the specifics of HTTP caching and in what scenarios to employ an HTTP cache header based strategy.,Once the concepts behind HTTP caching are understood the next step is to implement them in your application. Most modern web frameworks make this a trivial task.,HTTP caching occurs when the browser stores local copies of web resources for faster retrieval the next time the resource is required. As your application serves resources it can attach cache headers to the response specifying the desired cache behavior.,When an item is fully cached, the browser may choose to not contact the server at all and simply use its own cached copy:

public resources can be cached not only by the end-user’s browser but also by any intermediate proxies that may be serving many other users as well.

Cache - Control: public
load more v
40%

In this post, I’ll focus on explaining how different headers influence the browser cache and how they relate to proxy servers.,In a production setup, you’re going to work with load balancers, proxies, and CDNs. At each of these steps, your headers can get modified, so it’s much easier to debug knowing your server sent correct headers in the first place.,Every time you visit my site, the browser fetches a fresh copy of the HTML file from the server, and only when there are new script srcs or link hrefs is the browser downloading a new asset from the server.,If you correctly set ETag or Last-Modified headers so that the browser can verify that it already has the recent version cached, you and your users are going to save on bandwidth. You can use it for HTML and service worker script.

Cache-Control

Cache - Control: no - store
load more v
22%

You configure CloudFront to forward headers by using a cache policy or an origin request policy. For more information, see Working with policies. ,Custom origin – You can configure CloudFront to cache based on the value of any request header except the following: ,Configuring caching based on the protocol of the request,Configure CloudFront to forward the following headers: Origin, Access-Control-Request-Headers, and Access-Control-Request-Method.

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

logo.jpg

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

Product

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

Acme

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

Apex

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

Product

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

logo.jpg

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

Product

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

logo.jpg

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

Product

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

Acme

You can configure CloudFront to forward headers to the origin, which causes CloudFront to cache multiple versions of an object based on the values in one or more request headers. To configure CloudFront to cache objects based on the values of specific headers, you specify cache behavior settings for your distribution. For more information, see Cache Based on Selected Request Headers.

For example, suppose viewer requests for logo.jpg contain a custom Product header that has a value of either Acme or Apex. When you configure CloudFront to cache your objects based on the value of the Product header, CloudFront forwards requests for logo.jpg to the origin and includes the Product header and header values. CloudFront caches logo.jpg once for requests in which the value of the Product header is Acme and once for requests in which the value is Apex.

Apex
load more v
60%

Django also works well with “downstream” caches, such as Squid and browser-based caches. These are the types of caches that you don’t directly control but to which you can provide hints (via HTTP headers) about which parts of your site should be cached, and how.,Django can store its cached data in your database. This works best if you’ve got a fast, well-indexed database server.,Additionally, cache_page automatically sets Cache-Control and Expires headers in the response which affect downstream caches.,The cache timeout set by cache_page takes precedence over the max-age directive from the Cache-Control header.

given a URL,
try finding that page in the cache
if the page is in the cache:
   return the cached page
else :
   generate the page
save the generated page in the cache(
   for next time)
return the generated page
load more v
48%

When testing and troubleshooting caching behavior, a browser may set request headers that affect caching in undesirable ways. For example, a browser may set the Cache-Control header to no-cache or max-age=0 when refreshing a page. The following tools can explicitly set request headers and are preferred for testing caching:,The Pragma: no-cache header must not be present if the Cache-Control header isn't present, as the Cache-Control header overrides the Pragma header when present.,The sample app adds headers to control caching on subsequent requests:,The preceding headers are not written to the response and are overridden when a controller, action, or Razor Page:

In Startup.ConfigureServices, add the Response Caching Middleware to the service collection:

public void ConfigureServices(IServiceCollection services) {
   services.AddResponseCaching();
   services.AddRazorPages();
}

Configure the app to use the middleware with the UseResponseCaching extension method, which adds the middleware to the request processing pipeline in Startup.Configure:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
   if (env.IsDevelopment()) {
      app.UseDeveloperExceptionPage();
   } else {
      app.UseExceptionHandler("/Error");
   }

   app.UseStaticFiles();
   app.UseRouting();
   // UseCors must be called before UseResponseCaching
   // app.UseCors("myAllowSpecificOrigins");

   app.UseResponseCaching();

   app.Use(async (context, next) => {
      context.Response.GetTypedHeaders().CacheControl =
         new Microsoft.Net.Http.Headers.CacheControlHeaderValue() {
            Public = true,
               MaxAge = TimeSpan.FromSeconds(10)
         };
      context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
         new string[] {
            "Accept-Encoding"
         };

      await next();
   });

   app.UseEndpoints(endpoints => {
      endpoints.MapRazorPages();
   });
}
  • Cache-Control: Caches cacheable responses for up to 10 seconds.
  • Vary: Configures the middleware to serve a cached response only if the Accept-Encoding header of subsequent requests matches that of the original request.
// using Microsoft.AspNetCore.Http;

app.Use(async (context, next) => {
   context.Response.GetTypedHeaders().CacheControl =
      new Microsoft.Net.Http.Headers.CacheControlHeaderValue() {
         Public = true,
            MaxAge = TimeSpan.FromSeconds(10)
      };
   context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
      new string[] {
         "Accept-Encoding"
      };

   await next();
});
  • Cache responses with a body size smaller than or equal to 1,024 bytes.
  • Store the responses by case-sensitive paths. For example, /page1 and /Page1 are stored separately.
services.AddResponseCaching(options => {
   options.MaximumBodySize = 1024;
   options.UseCaseSensitivePaths = true;
});

When not using the [ResponseCache] attribute, response caching can be varied with VaryByQueryKeys. Use the ResponseCachingFeature directly from the HttpContext.Features:

var responseCachingFeature = context.HttpContext.Features.Get<IResponseCachingFeature>();

if (responseCachingFeature != null)
{
    responseCachingFeature.VaryByQueryKeys = new[] { "MyKey" };
}
load more v

Other "cache-header" queries related to "JSON Cache Header on Browser doesn't work"