How can I generate signed URLs for accessing Firebase Storage images?

1.7k Views Asked by At

I am making a web service with sveltekit and firebase. By the way, when users save images on firebase storage and other users try to use these images, I want to create a signed url and show it on the page to prevent Hotlink.

I searched and found that there is a function called getSignedUrl that generates a signed url, but there is no official document page that describes it in the firebase document.

Where can I get some example functions or information related to this?

2

There are 2 best solutions below

6
Frank van Puffelen On BEST ANSWER

The Firebase SDK for Cloud Storage uses a different type of URL, called a download URL. You can generate a download URL by calling getDownloadURL with/on a reference to the file, as shown in the documentation on downloading data through a URL.

0
Viewee On

The code below is the code I wrote on firebase functions using Firebase SDK. This code shows you using a function called getSignedUrl to write an url with an expiration date. I don't know why the official document doesn't have this information.

const { onObjectFinalized } = require('firebase-functions/v2/storage');
const { getStorage } = require('firebase-admin/storage');
const path = require('path');

const admin = require('firebase-admin');
const serviceAccount = require('./name-firebase-adminsdk.json');
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: '~~~~',
});
exports.generateThumbnail = onObjectFinalized(
    { cpu: 2, region: 'asia-northeast3' },
    async (event) => {
        const fileName = path.basename(filePath);
        const filePath = event.data.name; // File path in the bucket.

        const fileBucket = event.data.bucket; // Storage bucket containing the file.
        const bucket = getStorage().bucket(fileBucket);

        // Prefix 'thumb_' to file name.
        const thumbFileName = `thumb_${fileName}`;
        const thumbFilePath = path.join(path.dirname(filePath) + '/thumbnail', thumbFileName);

        const thumbnailFile = bucket.file(thumbFilePath);
        const expirationDate = new Date();
        expirationDate.setMinutes(expirationDate.getMinutes() + 1);

        const thumbnailURLArr = await thumbnailFile.getSignedUrl({
            action: 'read',
            expires: expirationDate,
        });
        const thumbnailURL = thumbnailURLArr[0];
    }
);

And, this is the page(captured img) showing Expired Token about url.

enter image description here