In this guide, you will learn how to generate pre-signed URLs for Amazon S3 with Astro on Cloudflare Workers. You will go through the process of setting up a new Astro project, enabling server-side rendering using the Cloudflare adapter, obtaining AWS credentials and then creating functions to generate pre-signed URLs for retrieval and upload from Amazon S3.
Let’s get started by creating a new Astro project. Open your terminal and run the following command:
Terminal window
npmcreateastro@latestmy-app
npm create astro is the recommended way to scaffold an Astro project quickly.
When prompted, choose:
Use minimal (empty) template when prompted on how to start the new project.
Yes when prompted to install dependencies.
Yes when prompted to initialize a git repository.
Once that’s done, you can move into the project directory and start the app:
Terminal window
cdmy-app
npmrundev
The app should be running on localhost:4321. Next, execute the command below to install the necessary library for building the application:
Terminal window
npminstallaws4fetch
The following library is installed:
aws4fetch: An AWS client for environments that support fetch and SubtleCrypto.
Integrate Cloudflare adapter in your Astro project
To generate pre-signed URLs for each object dynamically, you will enable server-side rendering in your Astro project via the Cloudflare adapter, execute the following command:
Terminal window
npxastroaddcloudflare
When prompted, choose the following:
Y when prompted whether to install the Cloudflare dependencies.
Y when prompted whether to make changes to the Astro configuration file.
You have successfully enabled server-side rendering in Astro.
To make sure that the output is deployable to Cloudflare Workers, create a wrangler.toml file in the root of the project with the following code:
wrangler.toml
name = "amazon-s3-astro-workers"
main = "dist/_worker.js"
compatibility_date = "2025-04-01"
compatibility_flags = [ "nodejs_compat" ]
[assets]
directory="dist"
binding="ASSETS"
[vars]
AWS_KEY_ID=""
AWS_REGION_NAME=""
AWS_S3_BUCKET_NAME=""
AWS_SECRET_ACCESS_KEY=""
Post that, make sure that you have both an .env file and a wrangler.toml file with the variables defined so that they can be accessed during npm run dev and when deployed on Cloudflare Workers respectively.
Further, update the astro.config.mjs file with the following to be able to access these variables in code programmatically:
In the navigation bar on the upper right in your AWS account, choose your user name, and then choose Security credentials.
Scroll down to Access keys and click on Create access key.
Again, click on Create access key.
Copy the Access key and Secret access key generated to be used as AWS_ACCESS_KEY_ID and AWS_ACCESS_KEY_SECRET respectively.
Configure Amazon S3 Bucket Policy
To securely share access to an Amazon S3 bucket, we need to configure a bucket policy that explicitly defines who can access the bucket and what actions they are allowed to perform. In this case, we want to grant a specific AWS account permission to both upload (PutObject) and download (GetObject) files from a particular S3 bucket. This is useful when you want another account-such as a partner, a separate environment, or a third-party integration-to programmatically interact with your bucket without making the contents public.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AuthenticatedReadUploadObjects",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<user-id>:root"
},
"Action": [
"s3:PutObject",
"s3:GetObject"
],
"Resource": "arn:aws:s3:::<bucket-name>/*"
}
]
}
In the configuration above, you have restricted the Get and Put operations to the user with the <user-id> ID and for the bucket <bucket-name>.
Configure Amazon S3 CORS
Since you will use pre-signed URLs to upload from client-side (browser) to Amazon S3, it becomes necessary to allow Amazon S3 to know that it should accept uploads from anywhere around the web.
NOTE: You can edit the AllowedOrigins to limit to specific domains, but in this case we’re worried less about the access level since we’re already enforcing IAM authentication while generating the pre-signed URLs.
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"PUT"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 9000
}
]
Generate the pre-signed URLs
1. Access the Environment Variables
The first step is to access the necessary environment variables during the runtime to create an AWS Client via aws4fetch. From Astro 5.6 and beyond, the way you want to access runtime environment variables in your code is by using the getSecret function from astro:env/server to keep things provider agnostic. This is crucial for storing sensitive information securely without hardcoding it into your application. You’ll retrieve the following variables:
Next, you’ll define the defineAws4Fetch function that creates an AWS client instance using the required environment variables. This function checks if the required AWS credentials are set and returns a new AwsClient instance configured for S3.
thrownewError(`AWS_KEY_ID OR AWS_SECRET_ACCESS_KEY environment variable(s) are not set.`)
}
returnnewAwsClient({
service: 's3',
accessKeyId,
secretAccessKey,
region: s3RegionName,
})
}
3. Determine S3 URLs
You’ll need to generate unique URLs for each file upload to Amazon S3. The getS3URL function below takes care of constructing the correct URL based on the file name, bucket name and the region.
src/storage/s3.ts
// ...Existing Code...
functiongetS3URL({ Key }: { Key:string }) {
if (!s3BucketName) {
thrownewError(`AWS_S3_BUCKET_NAME environment variable(s) are not set.`)
The getS3ObjectURL function below retrieves an object’s pre-signed URL from Amazon S3. It generates a signed request that allows you to access the file securely.
The uploadS3ObjectURL function below is responsible for generating a pre-signed URL for uploading a file to Amazon S3. It follows a similar structure to the getS3ObjectURL function, generating a signed URL that allows you to upload files securely.
In this blog post, you learned how to integrate Amazon S3 with Astro and Cloudflare Workers for file uploads and retrieval. By following the implementation steps, you can securely upload and retrieve files from Amazon S3, ensuring that your web application has a robust and flexible storage solution.
If you would like to explore specific sections in more detail, expand on certain concepts, or cover additional related topics, please let me know, and I’ll be happy to assist!