1
votes

I have some publicly available files in a google cloud storage bucket, the links are on a static site. I'd like to log when a user downloads the files, whilst making the link behave like a normal download link.

My initial idea is to use the link to call a cloud function and pass it the object name. The cloud function can do whatever logging logic it needs to, and also pass the file to the client.

My question is about how to pass the file to the client as if they'd just clicked on a normal download link. I think I need to insert some headers, maybe?

1
I'm aware that you can setup logging for a bucket, but I'm looking for information about how to intercept a download request and still pass the requested file to the client.John

1 Answers

1
votes

You can use HTTP functions to log the event and then redirecting user to the actual Google Cloud Storage link. For this would have to use the Cloud function's URL as the user facing URL along with a file identifier param.

Here's a sample function:

exports.downloadFile = (req, res) => {
  const {fileId} = req.query
  // TODO: Get the file URL
  // TODO: Log the event
  res.redirect(FILE_URL);
};

Your function's URL would look something like this:

https://[FN_REGION]-[PROJECT_ID].cloudfunctions.net/[FN_NAME]?fileId=the_file_id

Here's the procedure:

  • When users click on download button, you must open this link in a new tab which will make a GET request to your Cloud function.

  • The function will then read fileId from query param, log the event and redirect user to the actual file URL in their browser.

This still requires the user to click the button once but gives them the actual download URL after the event is logged.