Search code examples
node.jsgoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-storagefirebase-storage

Firebase Storage access token creation in node.js


Basically I have two ways of uploading files to the firebase storage:

  1. Frontend calls backend with image url, the backend downloads the image and uploads via bucket.upload (which I like, because I can set the storageAccessToken)
  2. The User uploads directly via frontend with a signed url that got generated in the backend. (which I dislike because I can't set a storageAccessToken)

I have a onFinalize trigger that gets called everytime a new object is stored in the firebase storage.
In this trigger I want to create a firestore doc for this particular object that got added.
In order to get the file information I use probe-image-size.
The problem is that I need a download link for the file and without a storageAccessToken I can not download the file as far as I know.

Basically the question is: can I add a storageAccessToken in the onFinalize trigger or could I add the storageAccessToken when I upload a file via frontend with the signedUrl?


Solution

  • If I correctly understand your question, you would like, in a Cloud Function ("onFinalize trigger") to create a Firestore document which contains, among other info (from probe-image-size), a signed URL.

    You can get a signed URL through a Cloud Function, as follows, without the need for a storageAccessToken:

    exports.generateSignedURL = functions.storage.object().onFinalize(async object => {
    
        try {
            const bucket = admin.storage().bucket(object.bucket);
            const file = bucket.file(object.name);
    
            const signedURLconfig = { action: 'read', expires: '08-12-2025' };  // For example...
    
            const signedURLArray = await file.getSignedUrl(signedURLconfig);
            const url = signedURLArray[0];
    
            await admin.firestore().collection('signedURLs').add({ fileName: object.name, signedURL: url })
            return null;
        } catch (error) {
            console.log(error);
            return null;
        }
    
    });