In this guide, we are going to look at how to put static assets into an AWS S3 Bucket. The goal being that we can use those assets in the front end of a website. Maybe as images or via CSS & JS. In order to be able to do this, we need two things:
- The objects in the bucket need to be publicly accessible.
- We need to allow CORS. (So that we don’t get the No Access-Control-Allow-Origin header is present)
Step 1: Remove “Block public access” : If you have an existing Bucket
If you have an existing S3 bucket, you will have to open up the bucket page on AWS and then go to the permissions tab as shown in the image below.
When you scroll down, you will see a section where you can edit the “block public access” settings. It should look something like this…
On clicking “edit”, you should reach a screen where you just need to “uncheck” the checkbox that says that all public access it blocked.
Step 1: “Block public access” Settings : If you are making a new bucket
When creating a new bucket, you will see the same settings to “block public access” which you need to UNCHECK.
When you uncheck this, a new section will pop up under it. You need to also need to CHECK the checkbox there to allow it…
Step 2: Set Bucket Policy To Allow Files To Be Read
For your bucket, go to the permissions tab…
Scroll down and find the Bucket policy section…
In the bucket policy section, edit it to enter the below JSON.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicRead", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::<YOUR BUCKET NAME HERE>/*" } ] }
Remember to replace the <YOUR BUCKET NAME HERE> with your bucket name.
The bucket policy is taken from here.
You can learn more about bucket policies by going here.
Step 2: Set CORS Settings To Prevent CORS errors
For your bucket, go to the permissions tab…
Scroll all the way to the bottom and then go to the Cross-origin resource sharing (CORS) section.
There, you need to hit “Edit” and enter the following JSON.
Here is the JSON for copy and paste…
[ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ]
Finally: How To Check If Things Are Working Right
This is simple. You can open up the console on Google Crome / Firefox & then run…
fetch('https://url_of_asset.jpeg')
You should get the following kind of responses…
And that’s it!