Search code examples
firebasegoogle-cloud-functionsgoogle-cloud-storage

getSignedUrl when using cloud functions


I am trying to get image url so that I can pass it as src in my html. I created functions and would like to send the url in response. I tried the below but I keep getting

Error: Cannot sign data without client_email.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

export const getPicURL = functions.https.onRequest(
    (request, response) => {
        const storageBucket = admin
            .storage()
            .bucket('gs://my-app.appspot.com');

        const fileName = 'my-app/pic1.jpg';
        const tomorrow = new Date(
            new Date().getTime() + 24 * 60 * 60 * 1000
        );

        const signedURL = storageBucket
            .file(fileName)
            .getSignedUrl({ action: 'read', expires: tomorrow });

        signedURL
            .then((data) => {
                response.send(data[0]);
            })
            .catch((err) => {
                console.log('My Error', err);
                response.sendStatus(500).send(err);
            });
    }
);

I feel like I am missing configuration step but I don't know where to add these properties


Solution

  • The issue I had is with service account. I was not initializing the app with proper config. I could find the details in https://console.firebase.google.com/ >> Project >> Settings >> Service Account >> Firebase Admin SDK

    firebase console

    firebase admin sdk

    Instead of just admin.initializeApp(); we need to do the following

    var admin = require("firebase-admin");
    
    var serviceAccount = require("path/to/serviceAccountKey.json");
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://my-app.firebaseio.com"
    });