You are viewing the preview version of this book
Click here for the full version.

Checking that the file exists

As there is no check that the file actually exists during the signing process, there are no guarantees that the resulting signed URL will be able to fetch the object. In some cases this can produce errors on the client-side as the backend will provide a valid URL but it still can't be downloaded. Depending on how files are uploaded to a bucket and how they are removed from it, this can be a problem.

The solution is to check the bucket if the object exists and only sign if it does. In this case, the frontend gets an error from the backend instead of from the bucket, which is easier to handle.

Fortunately, there is no need to download the object on the backend just to check its existence as there is a HeadObject call just for this. This only fetches the metadata of the object and returns an error if it does not exist or it can't be read.

const s3FileExists = async (bucket, key) => {
  try {
    await s3.send(new HeadObjectCommand({
      Bucket: bucket,
      Key: key,
    return true;
  }catch(e) {
    // how to check?

If the object exists, HeadObjectCommand returns the metadata, and if it does not it throws an error. Permission-wise, it requires the same s3:GetObject that is needed for the download.

But how to distinguish an object not found from a more general error which can happen for all sorts of reasons? Maybe the network got disconnected for a short while, or the object exists but there was problems with permissions. There is a wide variety of reasons the call returns an error and making a conclusion that the file does not exist may lead to errors down the road.

But this should be an easy task: the returns the reason why the request returned an error, and we just need to distinguish the case where it's because the object is not found and rethrow the error otherwise.

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions