In this tutorial, I will show you how to set up the Amazon S3 Upload Provider Plugin for your Strapi App.
You will first set up and configure an S3 storage bucket for your app. Then, you'll create a Strapi App. Next, you will install and configure the Amazon S3 Upload Provider Plugin. Finally, you will test the plugin by uploading some images to your Strapi backend.
By the end of this tutorial, you should be able to use the Amazon S3 Upload Provider Plugin with any Strapi project.
Strapi is the leading open-source headless Content Management System (CMS). It is 100% JavaScript, based on Node.js, and used to build RESTful APIs and GraphQL. It also has a cloud SAAS, Strapi Cloud- a fully managed, composable, and collaborative platform to boost your content velocity!
Strapi enables developers to build projects faster by providing a customizable API out of the box and giving them the freedom to use their favorite tools. Content teams use Strapi to autonomously manage all types of content and distribute it from one CMS to any channel be it websites, mobile apps, or connected devices.
A powerful feature of Strapi is its flexibility and extensibility. This is provided through plugins hosted on the Strapi Market. Plugins help add more functionality to your Strapi app. One such feature is uploading your media assets to a cloud provider using the Strapi dashboard.
Sometimes, you may want to host your app's media files in a different location from where your Strapi app is hosted. This is useful to save on storage, memory, and compute resource usage. Also, you can leverage cloud-based solutions like Content Delivery Networks (CDN) and cloud storage buckets for faster and more reliable loading of your media assets.
Amazon AWS is the biggest cloud provider. It offers Amazon S3, a cloud storage service to host your media assets. Amazon S3 is scalable, reliable, secure, and performant. The Strapi Team built an Amazon S3 Upload Provider Plugin to help with uploading your media assets to your S3 storage bucket.
To follow along with this tutorial you need the following:
Knowledge Prerequisites:
Software Prerequisites:
*npm*
or *yarn*
.)Hardware Prerequisites
Additional Prerequisites You will also need an AWS Account. A credit card is required to open one. AWS offers a 12-month free trial to test out the Amazon S3 bucket with 5GB of free storage.
We will start off by creating a Strapi app.
NOTE: If you prefer testing the ready-made app, you can clone the Github repo.
cd $HOME
strapi-aws-s3
. mkdir strapi-aws-s3
strapi-aws-s3
. cd strapi-aws-s3
npx create-strapi-app backend --quickstart
OR
yarn create strapi-app backend --quickstart
This command creates your Strapi app in the folder named backend
. The --quickstart
flag sets up your Strapi app with an SQLite database.
Your folder structure in strapi-aws-s3
after installing Strapi should look similar to this:
1 .
2 ├── backend
3 │ ├── build
4 │ ├── .cache
5 │ ├── config
6 │ ├── data
7 │ ├── database
8 │ ├── .editorconfig
9 │ ├── .env
10 │ ├── .env.example
11 │ ├── .eslintignore
12 │ ├── .eslintrc
13 │ ├── favicon.ico
14 │ ├── .gitignore
15 │ ├── node_modules
16 │ ├── package.json
17 │ ├── public
18 │ ├── README.md
19 │ ├── src
20 │ ├── .strapi-updater.json
21 │ ├── .tmp
22 │ └── yarn.lock
23 ├── .git
24 ├── LICENSE
25 └── README.md
After installation, your app should start automatically. Visit http://localhost:1337/admin in your browser and register your details in the Strapi Admin Registration Form.
NOTE: If Strapi did not start automatically, run these commands:
cd backend
npm run develop
OR
cd backend
yarn develop
npm run develop
starts your Strapi project development server in watch mode. Watch mode changes in your Strapi project will trigger a server restart.
Creating a new user logs you into the Strapi Dashboard.
The left-hand side of the Strapi dashboard lists the Content Manager containing your content types. The PLUGINS option lists the plugins installed in your project. Content-Type Builder Plugin and Media Library Plugin are installed by default in your Strapi app.
The Media Library Plugin is what you will use to upload images to your Amazon S3 bucket. If the Amazon S3 Upload Provider Plugin is working, images you upload in the Media Library should appear in your S3 bucket automatically.
Install AWS S3 Provider
Stop your strapi server by pressing Ctrl+C
in your terminal. Install @strapi/provider-upload-aws-s3
:
cd backend
npm install @strapi/provider-upload-aws-s3 --save
OR
cd backend
yarn add @strapi/provider-upload-aws-s3
Create a file named plugins.js
in your config
folder
touch config/plugins.js
Add this configuration code to plugins.js
:
1 // ~/strapi-aws-s3/backend/config/plugins.js
2
3 module.exports = ({ env }) => ({
4 upload: {
5 config: {
6 provider: 'aws-s3',
7 providerOptions: {
8 accessKeyId: env('AWS_ACCESS_KEY_ID'),
9 secretAccessKey: env('AWS_ACCESS_SECRET'),
10 region: env('AWS_REGION'),
11 params: {
12 ACL: env('AWS_ACL', 'public-read'),
13 signedUrlExpires: env('AWS_SIGNED_URL_EXPIRES', 15 * 60),
14 Bucket: env('AWS_BUCKET'),
15 },
16 },
17 actionOptions: {
18 upload: {},
19 uploadStream: {},
20 delete: {},
21 },
22 },
23 },
24 });
This enables the plugin to work in your app.
AWS_ACCESS_KEY_ID
, AWS_ACCESS_SECRET
, AWS_REGION
, and AWS_BUCKET
are environment variables. You will later assign their values in the .env
file for your Strapi project after setting up the Amazon S3 bucket.
Due to the default settings in the Strapi Security Middleware, you will need to modify the contentSecurityPolicy
settings to see thumbnail previews in the Media Library properly. You should replace strapi::security
string with the object below instead as explained in the middleware configuration documentation.
Edit the middlewares.js
file in your config
folder:
1 // ~/strapi-aws-s3/backend/config/middlewares.js
2
3 module.exports = [
4 'strapi::errors',
5 /* Replace 'strapi::security', with this snippet */
6 /* Beginning of snippet */
7 {
8 name: 'strapi::security',
9 config: {
10 contentSecurityPolicy: {
11 useDefaults: true,
12 directives: {
13 'connect-src': ["'self'", 'https:'],
14 'img-src': [
15 "'self'",
16 'data:',
17 'blob:',
18 'dl.airtable.com',
19 'yourBucketName.s3.yourRegion.amazonaws.com',
20 ],
21 'media-src': [
22 "'self'",
23 'data:',
24 'blob:',
25 'dl.airtable.com',
26 'yourBucketName.s3.yourRegion.amazonaws.com',
27 ],
28 upgradeInsecureRequests: null,
29 },
30 },
31 },
32 },
33 /* End of snippet */
34 'strapi::cors',
35 'strapi::poweredBy',
36 'strapi::logger',
37 'strapi::query',
38 'strapi::body',
39 'strapi::session',
40 'strapi::favicon',
41 'strapi::public',
42 ];
Later you will replace 'yourBucketName.s3.yourRegion.amazonaws.com'
with the link to your S3 bucket. Refer to AWS S3 | Strapi Market for more information on configuring the plugin.
The next step here is to set up AWS as part of our project.
Sign up for an AWS account on the AWS Console - Signup page if you don’t have one already. Refer to the Create and activate an AWS account guide for additional information related to the AWS account creation process.
Best practices for using AWS Amazon services state to not use your root account user and to use instead the IAM (AWS Identity and Access Management) service. Your root user is therefore only used for a very few select tasks. For example, for billing, you create an Administrator user and Group for such things. Other routine tasks can also be done with a regular IAM User.
Follow the “Creating your first IAM admin user and user group - AWS Identity and Access Management” guide to create an IAM admin user and user group using your AWS root account in the AWS Management Console.
Strapi-Admin
.Programmatic access
and AWS Management Console access
.Autogenerate a password
or click Custom password
and provide one.uncheck
the Require password reset.Next: Permissions
.Follow the steps below to set up permissions for Amazon S3.
Create group
and name it. Then, choose appropriate policies under Policy Name:s3
and check AmazonS3FullAccess
.Create group
.Add user to group
and check the Developers
group to add the new user.Next: Tags
.Add user to group
and check the Developers
group to add the new user.This step is optional and based on your workflow and project scope. To begin, click Next: Review
.
Retrieve Credentials 'Access Key ID' and 'Secret Access Key'**
Review the information and ensure it is correct. Use Previous
to correct anything. If satisfied, click Create user
.
If you do not do these steps, you must reset your Access key ID
and Secret access key
later.
Download the .csv
file and store it in a safe place. This contains the username, login link, access key ID, and secret access key. You can decide to keep these details in your password manager.
AWS Management Console Access sign-in link
. This will log you out of Administrator
.For more information, check out creating a regular user for the creation and management of your Strapi project.
Log into your AWS Management Console
as the new user you just created Strapi-Admin
.
Go to Services, click All services, scroll down, and select S3 Scalable Storage in the Cloud to open up the Amazon S3 Console.
Click on Create bucket in the Amazon S3 console.
Give your bucket a unique name. I named mine strapi-aws-s3-images-bucket
. Select the most appropriate region for your bucket.
For Object Ownership, select ACLs enabled to enable access to the S3 bucket from your Strapi backend. Select Bucket owner preferred for the plugin to work.
Under Block Public Access settings for this bucket, do the following:
Leave the rest of the settings as is and click Create bucket. Your new bucket should now be listed in the Amazon S3 Console.
Update your Strapi backend with new credentials from your newly created S3 bucket. Update .env
with the following:
1 # ~/strapi-aws-s3/backend/.env */
2 # Add this after the last line
3
4 AWS_ACCESS_KEY_ID=<Access Key ID>
5 AWS_ACCESS_SECRET=<Secret access key>
6 AWS_REGION=eu-west-2
7 AWS_BUCKET=strapi-aws-s3-images-bucket
NOTE: Replace the AWS credentials with the credentials in the .csv file you downloaded after creating an IAM role for your S3 bucket. For AWS_REGION input the region where your bucket is hosted. My bucket is hosted at eu-west-2.
Update the middlewares.js
file in your config
folder by replacing yourBucketName.s3.yourRegion.amazonaws.com
with the link to your S3 bucket. In my case the link becomes strapi-aws-s3-images-bucket.s3.eu-west-2.amazonaws.com
like so:
1 // ~/strapi-aws-s3/backend/config/middlewares.js
2
3 module.exports = [
4 'strapi::errors',
5 {
6 name: 'strapi::security',
7 config: {
8 contentSecurityPolicy: {
9 useDefaults: true,
10 directives: {
11 'connect-src': ["'self'", 'https:'],
12 'img-src': [
13 "'self'",
14 'data:',
15 'blob:',
16 'dl.airtable.com',
17 'strapi-aws-s3-images-bucket.s3.eu-west-2.amazonaws.com', // change here
18 ],
19 'media-src': [
20 "'self'",
21 'data:',
22 'blob:',
23 'dl.airtable.com',
24 'strapi-aws-s3-images-bucket.s3.eu-west-2.amazonaws.com', // change here
25 ],
26 upgradeInsecureRequests: null,
27 },
28 },
29 },
30 },
31 'strapi::cors',
32 'strapi::poweredBy',
33 'strapi::logger',
34 'strapi::query',
35 'strapi::body',
36 'strapi::session',
37 'strapi::favicon',
38 'strapi::public',
39 ];
Build your backend and start your server.
npm run build
npm run develop
#OR
yarn build
yarn develop
Visit the Media Library plugin page, http://localhost:1337/admin/plugins/upload. Click + Add new assets. Browse for an image you want to add from your computer and select Upload 1 asset to the library.
In a few moments, you should see your newly uploaded image in your Media Library as well as your Amazon S3 Bucket.
Visit https://s3.console.aws.amazon.com/s3/buckets/?region=** to see the newly uploaded image in your S3 bucket.
Delete the image from the Media Library. The image is automatically deleted from the Amazon S3 bucket.
Confirm the deletion by refreshing the link to your bucket. The bucket is now empty. Deleting the image from the Strapi Admin Dashboard worked.
You have successfully set up the Amazon S3 Upload Provider Plugin.
You can edit your middleware.js
so that it uses environment variables for the img-src
and media-src
attributes like so:
1 // ~/strapi-aws-s3/backend/config/middlewares.js
2
3 module.exports = [
4 'strapi::errors',
5 {
6 name: 'strapi::security',
7 config: {
8 contentSecurityPolicy: {
9 useDefaults: true,
10 directives: {
11 'connect-src': ["'self'", 'https:'],
12 'img-src': [
13 "'self'",
14 'data:',
15 'blob:',
16 'dl.airtable.com',
17 `${process.env.AWS_BUCKET}.s3.${process.env.AWS_REGION}.amazonaws.com`,
18 ],
19 'media-src': [
20 "'self'",
21 'data:',
22 'blob:',
23 'dl.airtable.com',
24 `${process.env.AWS_BUCKET}.s3.${process.env.AWS_REGION}.amazonaws.com`,
25 ],
26 upgradeInsecureRequests: null,
27 },
28 },
29 },
30 },
31 'strapi::cors',
32 'strapi::poweredBy',
33 'strapi::logger',
34 'strapi::query',
35 'strapi::body',
36 'strapi::session',
37 'strapi::favicon',
38 'strapi::public',
39 ];
Update the CORS configuration for your S3 bucket so that the thumbnails for your media uploads can be displayed in your Strapi Admin Dashboard.
Go to your Strapi App bucket in your Amazon S3 console and select the Permissions tab.
Scroll down to the Cross-origin resource sharing (CORS) block and select Edit
Add the following JSON for CORS configuration.
1 [
2 {
3 "AllowedHeaders": ["*"],
4 "AllowedMethods": ["GET"],
5 "AllowedOrigins": ["*"],
6 "ExposeHeaders": [],
7 "MaxAgeSeconds": 3000
8 }
9 ]
This rule will allow GET requests from any origin which includes your Strapi backend. For more information check out Strapi S3 Bucket CORS Configuration and Amazon S3 CORS Configuration.
Click on Save changes and your updated CORS configuration should be like this:
NOTE: In production, update the "AllowedOrigins" to your STRAPI URL
In this tutorial, we created a Strapi project and then installed and configured the AWS S3 provider for Strapi uploads (@strapi/provider-upload-aws-s3
) plugin in our Strapi project folder. We then created an Amazon S3 bucket with the recommended IAM policies to manage it.
Finally, we tested our app and saw the ease with which we can upload and delete images in the Amazon S3 bucket using the Strapi Admin Media Library. Check out the Github project repo.
I hope this tutorial has provided enough information and insight to help you confidently set up the Amazon S3 provider. If you have any issues, feel free to comment. The Strapi community is always available for any issues.
The Strapi experience has always been about flexibility, customization, and open-source innovation. But we understand that managing infrastructure and scaling your application can sometimes be a daunting task, diverting your focus from what you do best: developing web experiences.
That's why we're excited to introduce Strapi Cloud, so you can leverage the same robust Strapi capabilities you love, but without the hassle of managing servers, worrying about uptime, or scaling infrastructure as your project grows. It will allow you to future-proof your apps with a CMS that meets the content management needs of all your stakeholders, no matter your use case, services or devices.
Strapi remains committed to open-source values, and self-hosting will always be a viable option. We believe in offering choices that align with your project's unique needs. Strapi Cloud is an additional resource for those who want to focus solely on development, leaving the infrastructure to us.
Aw are here to support you every step of the way, no matter which hosting option you choose. You can reach out to us and the community on our Discord if you have any questions!
Mark Munyaka is a freelance web developer and writer who loves problem-solving and testing out web technologies. You can follow him on Twitter @McMunyaka