VueJS/browser caching production builds

Solution 1:

We struggled with this same issue and found that some people's browsers would not even pull the latest version unless they manually refreshed. We had problems with caching at various layers, including the CDN where we hosted files.

We also struggled with maintaining versions and being able to rapidly redeploy a previous version if something goes wrong.

Our solution (using project based on vue-cli Webpack):

1) We build the distribution to have a version specific folder instead of 'static'. This also helps us track builds and 'undo' a deployment if needed. To change the 'static' directory, change 'assetsSubDirectory' under 'build' in index.js and change 'assetsPublicPath' to your CDN path.

2) We use Webpack Assets Manifest to build a manifest.json file pointing to all the assets. Our manifest includes a hash of all files, as its a high security application.

3) We upload the versioned folder (containing the js and css) to our CDN.

4) (Optional) We host a dynamic index.html file on the backend server. The links to the stylesheet and scripts are filled in by the backend server using a template system pulled from the data on the manifest.json (see #5). This is optional as you could use the force-reload option as in the comment below, which isn't a great experience but does work.

5) To publish a new version, we post the manifest.json to the backend server. We do this via a GraphQL endpoint but you could manually put the json file somewhere. We store this in the database and use it to populate the index.html and also use it to verify files using the file hash (to validate our CDN was not hacked).

Result: immediate updates and an easy ability to track and change your versions. We found that it will immediately pull the new version in almost all user's browsers.

Another bonus: We are building an application that requires high security and hosting the index.html on our (already secured) backend enabled us to more easily pass our security audits.


Edit 2/17/19

We found that corporate networks were doing proxy caching, despite no-cache headers. IE 11 also seems to ignore cache headers. Thus, some users were not getting the most up to date versions.

We have a version.json that is incremented/defined at build time. Version number is included in manifest.json. The build bundle is automatically uploaded to S3. We then pass the manifest.json to the backend (we do this on an entry page in Admin area). We then set the "active" version on that UI. This allows us to easily change/revert versions.

The backend puts the "currentVersion" as a Response Header on all requests. If currentVersion !== version (as defined in version.json), then we ask the user to click to refresh their browser (rather than force it on them).

Solution 2:

Based on this comprehensive answer on cache headers, your best bet is going to be solving this on the server side if you have control of it, as anything in the <meta> tags will get overridden by headers set by the server.

The comments on the question indicate that you are serving this app with nginx. Using the linked answer above, I was able to set the Cache-Control, Expires and Pragma headers for any requests for files ending in .html this way in my nginx config:

server {

  ...other config

  location ~* \.html?$ {
    expires -1;
    add_header Pragma "no-cache";
    add_header Cache-Control "no-store, must-revalidate";
  }
}

This successfully forces the browser to request the latest index.html on every page reload, but still uses the cached assets (js/css/fonts/images) unless there are new references in the latest html response.

Solution 3:

This problem is annoying, no doubt. Had to solve it using a custom Front end version endpoint sent in the header. I am using a rails backend and Vue + Axios as front-end. Note I don't need a service worker and hence not using one.

Essentially I am just reloading whenever there is a get request and that the version of the application has changed (the server can inform the same)

axiosConfig.js

axios.interceptors.response.use(
  (resp) => {
    const fe_version = resp.headers['fe-version'] || 'default'
    if(fe_version !== localStorage.getItem('fe-version') && resp.config.method == 'get'){
      localStorage.setItem('fe-version', fe_version)
      window.location.reload() // For new version, simply reload on any get
    }
    return Promise.resolve(resp)
  },
)

Rails Backend

application_controller.rb

after_action :set_version_header

def set_version_header
  response.set_header('fe-version', Setting.key_values['fe-version'] || 'default')
end

application.rb (CORS config assuming Vue running on port 8080)

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins ['localhost:8080', '127.0.0.1:8080']
    resource '*', expose: ['fe-version'], headers: :any, methods: [:get, :post, :delete, :patch], credentials: true
  end
end if Rails.env.development?

Wrote a detailed article here: https://blog.francium.tech/vue-js-cache-not-getting-cleared-in-production-on-deploy-656fcc5a85fe

Solution 4:

To delete the cache you can run rm -rf node_modules/.cache

This deletes your cache. You can run a new build before deploying.

I was having the same issue where I ran a production build, but then even when running locally my code would point to the production build instead of my latest changes.

I believe this is a related issue: https://github.com/vuejs/vue-cli/issues/2450

Solution 5:

If you use asp.net core you can try the following trick among with the webpack which generates js files with the hash at the end of the name eg. my-home-page-vue.30f62910.js. So your index.html contains: <link href=/js/my-home-page-vue.30f62910.js rel=prefetch> which means whenever you change the my-home-page.vue it will generate a new hash in the filename.

The only thing you need is to add a cache restriction against the index.html

In your Startup.cs:

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    // ....
    app.UseStaticFiles(new StaticFileOptions
    {
      // Make sure your dist folder is correct
      FileProvider = new PhysicalFileProvider(Path.Combine(_env.ContentRootPath, "ClientApp/dist")),
      RequestPath = "",
      OnPrepareResponse = context =>
      {
        if (context.Context.Request.Path.StartsWithSegments("/index.html", StringComparison.OrdinalIgnoreCase))
        {
          context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
          context.Context.Response.Headers.Add("Expires", "-1");
        }
      },
    });
    // ....
}