Chatwithcloud logo

ChatWithCloud

AWS GenAI Tools

Creating a Pre-signed S3 URL for Uploading Files Using TypeScript and AWS SDK V2

Code

Below is the TypeScript code snippet making use of AWS SDK's S3 client to generate a pre-signed URL:

import { S3 } from 'aws-sdk'; async function generatePreSignedUrl() { const s3 = new S3(); const params = { Bucket: 'Bucket-name', Key: 'Test.txt', Expires: 60, }; try { const url = await s3.getSignedUrlPromise('putObject', params); console.log(url); } catch(s3Error) { console.log(s3Error); } } generatePreSignedUrl();

Detailed Code Explanation

  1. We start by importing 'S3' from the 'aws-sdk'.
  2. Next, we declare an async function generatePreSignedUrl where we will interact with AWS S3.
  3. An instance of the S3 service interface is created using const s3 = new S3();.
  4. Then, we define the parameters required to create the pre-signed URL. The 'Bucket' and 'Key' attributes are the name of your S3 bucket and the file name respectively. 'Expires' attribute is the duration in seconds after which the generated URL will expire.
  5. We then call s3.getSignedUrlPromise passing in the operation 'putObject' and our parameters.
  6. On a successful response from AWS S3, we log the pre-signed URL else we log the error message.

Expected Output

When you run the script, the console will print out a URL that looks like this:

"https://Bucket-name.s3.amazonaws.com/Test.txt?AWSAccessKeyId=<access-key>&Expires=<expiry-time>&Signature=<generated-signature>"

Considerations & Caveats

Required IAM Permissions

Your IAM user needs the s3:PutObject permission on the specific S3 bucket.

Example IAM Policy:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::Bucket-name/*" } ] }

FAQ

Q1: What is a pre-signed URL?

A pre-signed URL is a URL that you generate with your AWS credentials that provides temporary access to upload or download files from specific S3 buckets.

Q2: How long can a pre-signed URL be valid?

By default, a pre-signed URL is valid for 15 minutes, however you can specify the expiration time (in seconds) when you generate a pre-signed URL. The maximum expiration time can be 7 days (604800 seconds).

Q3: What will happen when the pre-signed URL expires?

Once the pre-signed URL expires, you will no longer be able to use it to upload/download files. Any attempt to use it will result in an error.

Q4: Why should I use pre-signed URLs?

Pre-signed URLs can provide a secure way to provide limited access to users for a specific task such as file-upload or download. They are easy to generate and manage.





Related articles
Monitor and Notify When Approaching Service LimitsGet Current IAM Identity TypeScriptCalculate the Size of Each S3 Bucket and Find the One with the Most Data