How to specify a Cache-Control header for index.html in create-react-app

10,130

Solution 1

As Evans mentioned this headers should be set from the server side. How you actually set the headers differs between backend programming languages/servers.

Here are a few examples:

  1. Node.js res.setHeader('Cache-Control', 'no-cache');
  2. Nginx add_header Cache-Control no-cache;

Solution 2

These headers would need to be set by the server which will be sending the content and setting the headers. These are HTTP headers and it is not handled in anyway in or with react.

Solution 3

You can specify different cache behaviour on the server / CDN from where you are serving your asset files.

Example: If you are using AWS S3 bucket, you can do so under the metadata properties of the object.

Ref: https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingMetadata.html#object-metadata

enter image description here

Share:
10,130

Related videos on Youtube

JimmyTheCode
Author by

JimmyTheCode

I'm training to be a junior software developer. Currently I'm building a portfolio in React, NodeJS with Express, and Postgres. I've worked in civil engineering and construction for about 10 years as an engineer and quantity surveyor.

Updated on September 14, 2022

Comments

  • JimmyTheCode
    JimmyTheCode over 1 year

    I'm trying to follow the guidance on create-react-app.dev's Production Build documentation:

    To deliver the best performance to your users, it's best practice to specify a Cache-Control header for index.html, as well as the files within build/static. This header allows you to control the length of time that the browser as well as CDNs will cache your static assets. If you aren't familiar with what Cache-Control does, see this article for a great introduction.

    Using Cache-Control: max-age=31536000 for your build/static assets, and Cache-Control: no-cache for everything else is a safe and effective starting point that ensures your user's browser will always check for an updated index.html file, and will cache all of the build/static files for one year. Note that you can use the one year expiration on build/static safely because the file contents hash is embedded into the filename.

    Is the correct way to do this to use HTML headers in index.html - eg something like:

    <meta http-equiv="Cache-Control" content="max-age: 31536000, no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    

    (Credit: this stack overflow response and this YouTube tutorial)

    If so, how do I follow the documentation's suggestion that I should set "max-age=31536000 for your build/static assets, and Cache-Control: no-cache for everything else"? I don't know how to set different controls for different assets.