Firebase hosting with cloud functions - how to purge/refresh CDN cache?

Brad Stanfield

I'm following the instructions from this video and so far things are working perfectly right up to the point where I need to purge the CDN of old HTML:

https://www.youtube.com/watch?v=7_2CJs_VZk4

So far I've created a static HTML page using Firebase Cloud Functions, and it is stored on Firebase Cloud Storage. Whenever data from my Firebase Database is updated, a new and updated static HTML page is rendered and is saved to the Cloud Storage.

Firebase Hosting serves that static HTML page, and it is stored on the CDN. As per the above video, I've set a long refresh time for the CDN because I only want it to update when I make a change to the data in Firebase Database (no refreshing the CDN if no change has been made)

For this to work, when the page is updated, the old HTML page stored on the CDN must be purged and replaced with the new HTML page.

The video at time 33:19 suggests the following code:

const purgeUrl = `${ORIGIN}/${path}`;
await request(purgeUrl, { method: "PURGE" });

Unfortunately it doesn't seem to work. I can see that the page has updated on Cloud Storage, but when I refresh the URL the new HTML page is not displayed. The only way I can show the new HTML is by re-deploying the firebase code again (terminal - firebase deploy).

Here is my code (in node.js):

const ORIGIN = "examplesite-30ccf.firebaseapp.com/";

function getFacts(){
  return database.ref('/web app/test').once('value').then(snap =>snap.val());
}

exports.updateHomePage = functions.database.ref('/web app/test')
.onWrite((snap, context) => {

  return getFacts()
  .then(result1 => {
    console.log("result1", result1);
      return bucket
      .file('public_html/index.html')
      .save(HomePage(result1), {
        gzip: true,
        metadata: {
          contentType: "text/html; charset=utf-8",
          cacheControl: "max-age=300, s-maxage=31536000" // indef CDN cache since we purge manually
        }
      }); 
  }).then(doNotUse => {

    const purgeUrl = `${ORIGIN}`;
    console.log("purged URL", purgeUrl);
    return request(purgeUrl, { method: "PURGE" });
}).catch(error => {
      // Handle errors of asyncFunc1() and asyncFunc2()
  });

});`

There is no crash or exceptions in the Firebase Functions logs. Any help is much appreciated. Thanks

Brad Stanfield

I inadvertently found the answer while trying to fix another issue.

You need to be on a paid Firebase plan to make external API calls: https://firebase.google.com/pricing/

So the PURGE method does work so long as you have upgraded you plan. Here is the code that allows you to purge the CDN (Node.js in Typescript):

import * as request from "request-promise";

const purgeUrl = `examplesite.com`;
await request(purgeUrl, { method: "PURGE" });

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Undeploy functions in firebase hosting

Firebase Cloud Functions access Firebase Hosting files

Firebase Hosting with dynamic cloud functions rewrites

Firebase Cloud Functions with Firebase Hosting : firebase.json "rewrites"

Can Firebase Hosting Serve Cached Data from Cloud Functions?

using "firebase deploy" to deploy to hosting - how does firebase know if it is deploying to hosting and not cloud functions?

Invalidate Google Cloud CDN cache from the backend

Downsides of firebase functions vs firebase hosting

Firebase Functions on Firebase Hosting: 404

Connect Google Cloud CDN with Google Cloud Functions

Data driven cache on Firebase with Cloud Functions SSR + Hosting?

Firebase: Cloud Functions, How to Cache a Firestore Document Snapshot

Can Firebase Cloud Functions Use an In-Memory Cache?

Rewrite ALL Firebase Cloud Functions to hosting

Direct Firebase Hosting to Cloud Functions deployed in other regions

Is it possible to cache Cloud Function invocation result in Firebase Hosting rewrite indepedently of the requested URL?

How to verify if a Cloud CDN response was a cache hit (or comes from CDN)

firebase hosting cache error

How to transfer wordpress hosting website to CDN?

Firebase Cloud Functions hosting, 'once' callback works in cloud functions but not in hosting site

Nuxt ssr with firebase hosting and functions

Vue.js SPA on Firebase Hosting with wildcard rewrite to Firebase Cloud Functions

Firebase Hosting proxy to Cloud Functions only triggers in us-central1

Firebase hosting custom domain 404 when forwarding requests to Cloud Functions

Firebase Hosting vs Storage - Serve Images with CDN

Firebase Cloud Functions: save TypeScript Map() - how?

How do I disable firebase functions cache?

how to render ssr project on firebase hosting without using functions?

What are the advantages of pairing Cloud Functions with Firebase Hosting?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive