Search code examples
azureazure-web-app-serviceazure-cdnazure-static-website-hosting

Azure Devops set max-age on index.html in Azure storage with Azure CDN on static web site


So, I don't want my index.html on my static vue.js app to always be cached because of updates. I can set max-age in the storage explorer manually. I have a Azure CDN set up for this site, which I purge after every deploy, but I don't think this will always update current users because the max-age on the index.html isn't set. Is there a way to set from CDN the max-age? Or is there a azure cli command that I should use on devops deploy to set the max-age on the index.html file in storage. I don't see much documentation on this, maybe the CDN just takes care of everything?


Solution

  • Make sure you set the correct values for both the "server-side caching" by the CDN and the "local caching" by your browser. You need to set Max-Age on the blob to have it be always current in the CDN, while using the Cache-Control header on the Blob to have the browser always read the current version. This is also known as "Internal Max Age" vs "External Max Age"(Cache-Control) in CDN, though the naming varies depending on the provider.

    See also my recent answer on this: How to stop index.html being cached by Azure CDN

    For me, I found it is usually sufficient to set the Cache-Control header in blob storage on the index.html in order to control both the server-side and the local caching. At least the Azure CDN Provider respects this for server-side as well, so you have minimal effort.

    See also this code example if you want to add it to your pipeline: https://schwabencode.com/blog/2019/05/03/Update-Azure-Storage-Blob-Properties-with-PowerShell

    # Storage Settings
    $storageAccount = "__storage account__";
    $containerName = "__container name__";
    
    # Blob Update Settings
    $contentCacheControl = "public, max-age=2592000"; # 30 days
    $extensions = @(".gif", ".jpg", ".jpeg", ".ico", ".png", ".css", ".js");
    
    # Read all blobs
    $blobs = az storage blob list --account-name $storageAccount --container-name $containerName --num-results * --output json | ConvertFrom-Json
    
    # iterate all blobs
    foreach($blob in $blobs)
    {
        # use name as identifier
        $blobName = $blob.name;
    
        # get extension
        $extension = [System.IO.Path]::GetExtension($blobName).ToLower();
     
        # update blob if extension is affected
        if($extensions.Contains($extension))
        {
            az storage blob update --account-name $storageAccount --container-name $containerName --name $blobName --content-cache-control $contentCacheControl
            Write-Host "Updated $blobName" 
        }
    }