React template index.html caching web hosting?

 This setup works for me

app.UseSpaStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = ctx =>
    {
        if (ctx.Context.Request.Path.StartsWithSegments("/static"))
        {
            // Cache all static resources for 1 year (versioned filenames)
            var headers = ctx.Context.Response.GetTypedHeaders();
            headers.CacheControl = new CacheControlHeaderValue
            {
                Public = true,
                MaxAge = TimeSpan.FromDays(365)
            };
        }
        else
        {
            // Do not cache explicit `/index.html` or any other files.  See also: `DefaultPageStaticFileOptions` below for implicit "/index.html"
            var headers = ctx.Context.Response.GetTypedHeaders();
            headers.CacheControl = new CacheControlHeaderValue
            {
                Public = true,
                MaxAge = TimeSpan.FromDays(0)
            };
        }
    }
});
app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";
    spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions()
    {
        OnPrepareResponse = ctx => {
            // Do not cache implicit `/index.html`.  See also: `UseSpaStaticFiles` above
            var headers = ctx.Context.Response.GetTypedHeaders();
            headers.CacheControl = new CacheControlHeaderValue
            {
                Public = true,
                MaxAge = TimeSpan.FromDays(0)
            };
        }
    };

    if (env.IsDevelopment())
    {
        //spa.UseReactDevelopmentServer(npmScript: "start");
        spa.UseProxyToSpaDevelopmentServer("http://localhost:3000");
    }
});

  • Does not cache index or client-side routing (that returns index)
    • Cache-Control: public, max-age=0
  • Caches all /static/* resources for 1 year (versioned/sha'd filenames like javascript bundles)
    • Cache-Control: public, max-age=31536000
  • Does not cache any other resources (manifest.jsonservice-worker.js, etc)
    • Cache-Control: public, max-age=0

The main issue I had before making this change was because there was not an explicit Cache-Control header but there was a Last-Modified header, browsers would use this to cache the response.

Finally, if neither header is present, then we look for a "Last-Modified" header. If this header is present, then the cache's freshness lifetime is equal to the value of the "Date" header minus the value of the "Last-modified" header divided by 10. This is the simplified heuristic algorithm suggested in RFC 2616 section 13.2.4.

Post a Comment