paint-brush
Adding a File Service Plugin to Your Medusa Store: An Essential Guideby@learndevts
233 reads

Adding a File Service Plugin to Your Medusa Store: An Essential Guide

by LearndevtoolsMay 9th, 2023
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Medusa is an open-source headless commerce solution. It offers out-of-the-box features like customer, product, shipping, tax and region management, and RMA Flow. This tutorial focuses on S3 file storage to store images and files uploaded in Medusa.
featured image - Adding a File Service Plugin to Your Medusa Store: An Essential Guide
Learndevtools HackerNoon profile picture

Headless commerce has been out there for a long while with Medusa being one of the best tool to offer modular components. Medusa’s composable architecture allows you to build a store with any framework or language of your choice hence providing a full customization ability. Medusa equally allows you to build a unique ecommerce experience by providing a set of tools and essential building blocks developers can add up to create a powerful ecommerce website. It offers out-of-the-box features like customer, product, shipping, tax and region management, and RMA Flow. In today’s tutorial, you will learn how to add a file service plugin in order to be able to add products to your Medusa store via the admin dashboard

What is Medusa

Medusa is an open-source set of tools that allow you to build amazing and reliable ecommerce websites. With more than 17.8k stars and 1.3k forks on GitHub, this headless commerce solution comes with a handful of commerce modules from basic to advanced and is freely available. Its well-written documentation also contributes to its success as there are step-by-step guidelines on how to add a module or plugins. Some popular plugins among others are payments, notifications, search and file service plugins.

What is a File Service Plugin

A file service plugin allows you to host files like images used in Medusa. You may face issues if you don’t use or set up a file service for your Medusa store properly. Medusa offers three different ways to manage file storage; S3, MinIo and Spaces. This tutorial solely focuses on S3 file storage to store images and files uploaded in Medusa.

S3 or Simple Storage Service is an object storage used to store and retrieve any amount of data from anyway and at any time. We will use Amazon S3 for this demonstration.

How to upload files into your Medusa store

Amazon keeps data as objects within a bucket. An object consists of a file and optional data that describes it. To store a file, you need to upload it in a bucket(Buckets are the containers for objects), once uploaded, you can set permissions on the object.

Now let’s get you to upload files in your Medusa projects quickly.

Prerequisites

If you have everything set up then follow the steps below to add a File Service Plugin to Your Medusa Store.

Step 1: Create an S3 Bucket

Login into your AWS account, search and select S3

In the next page, Click on Create bucket

In the window that opens, provide the information necessary to create your bucket.


General Configuration

Provide a name to your bucket and leave the default region or choose another one per your requirements.

Object Ownership

For ownership, allow objects in the bucket to be owned by your account.

In the Block Public Access settings, uncheck Block all public Access. Doing this will show a warning message check the box in the message as in the image.

As for the Bucket versioning, tags, default encryption and advanced settings, leave the default settings or change them per your project requirements and click on Create bucket.

Step 2: Manage Policies

The next step consists of managing your created bucket policies. Head to the page of your bucket and open the permission tab. Then scroll down to the bucket policy section, click on edit, add the code below and Save.

{
 "Version": "2012-10-17",
 "Id": "Policy1397632521960",
 "Statement": [
   {
     "Sid": "Stmt1397633323327",
     "Effect": "Allow",
     "Principal": {
       "AWS": "*"
     },
     "Action": "s3:GetObject",
     "Resource": "arn:aws:s3:::<YOUR_BUCKET_NAME>/*"
   }
 ]
}

Replace <YOUR_BUCKET_NAME> with the name of your bucket. Here it is medusastorebucket

Step 3: Attach a Policy

In your account navigate to IAM and select Access Management->Policies in the left menu.

If this is your first time choosing a policy, then you will see a Welcome to Manage Policies Page and select get started else choose Create policy.

Then select the JSON tab and add the following code:

{
  "Version": "2012-10-17",
  "Statement" : [
    {
      "Effect" : "Allow",
      "Action" : [
        "action-statement"
      ],
      "Resource" : [
        "resource-statement"
      ]
    },
    {
      "Effect" : "Allow",
      "Action" : [
        "action-statement"
      ],
      "Resource" : [
        "resource-statement"
      ]
    }
  ]
}

Substitute the action-statement and resource-statement per your requirement and click on Next:tag


Learn more about Policies and permissions

Tags are optional so you can skip this step and click on the review button to review your policy.


Next, provide a name and description for your policy then click on Create policy


Now that you have created your policy, you need to attach it to a user group, navigate to Amazon console and choose User Groups. Select the name of the group then open the Permission tab

Choose Add permission and then attach policies

In the window that opens, select the policy you want to attach and click on add permission at the bottom of the page.

Step 4: Get Your Access Key

You need to obtain your access key in order to integrate the S3 Plugin into your project. You will need two elements; Access Key ID and Secret Access Key.


To get your AWS Access Key ID and Secret Access Key, head to your Amazon console on the left navigation, and choose Users.


Choose your IAM user name and open the Security credentials tab


Scroll down to Access Keys and click on Create Access Key


In the next window, you will be asked to choose where you want to use the access key. Check Local code if you are working in a local dev environment.


By choosing local a warning message will appear asking you if you understand the recommendation. Check the box and click on the next button.


Finally, add a tag description if you like to add one and click on Create access key

In the next window, you will see your Access and Secret Access key. Kindly copy and paste it somewhere on your PC since you will use it in the next step or download the CSV file.


Step 5: Install the S3 Plugin

Now that you have set up your bucket and created your access keys, it’s time to install the S3 plugin. To do so head to your Medusa backend folder and install it with the following command:

yarn add medusa-file-s3

Or

npm install medusa-file-s3


Then open your .env file and add the following

S3_URL=<YOUR_BUCKET_URL>
S3_BUCKET=<YOUR_BUCKET_NAME>
S3_REGION=<YOUR_BUCKET_REGION>
S3_ACCESS_KEY_ID=<YOUR_ACCESS_KEY_ID>
S3_SECRET_ACCESS_KEY=<YOUR_SECRET_ACCESS_KEY>


Where

  • <YOUR_BUCKET_URL> is the URL of your bucket. It is in the form https://<BUCKET_NAME>.s3.<REGION>.amazonaws.com. Where <BUCKET_NAME> is the name of your bucket, <REGION> the region.
  • <YOUR_BUCKET_NAME> is the name of the bucket created
  • <YOUR_BUCKET_REGION> the region of your bucket
  • <YOUR_ACCESS_KEY_ID> is your Access Key
  • <YOUR_SECRET_ACCESS_KEY> is your Secret Key


Finally in your medusa-config.js add the following code:

const plugins = [
  // ...
  {
    resolve: `medusa-file-s3`,
    options: {
        s3_url: process.env.S3_URL,
        bucket: process.env.S3_BUCKET,
        region: process.env.S3_REGION,
        access_key_id: process.env.S3_ACCESS_KEY_ID,
        secret_access_key: process.env.S3_SECRET_ACCESS_KEY,
    },
  },
]


Note that if you have many storage plugins configured, then the last plugin declared will be used. So if you want S3 to be used make sure it’s the last storage plugin added.

Step 6: Testing the Plugin

Now that you have successfully added your plugin. It’s time to test to make sure that everything is in the right place. You can use REST APIs or the Medusa Admin to test.


Navigate to your admin and backend folders respectively and run the following command:

// admin 
yarn run start
// backend
yarn run start

The default admin email and password are [email protected] and supersecret respectively. Open your admin panel with http://localhost:7000/


In the menu click on Products then Add Product. Provide details for your product and publish it.

Lastly, you need to add a configuration in your storefront that adds the S3 bucket domain name into the configured images’ domain names if you are using NextJS storefront. If you don’t do it you will receive the following error next/image Un-configured Host.


So in your next.config.js add the following:

const { withStoreConfig } = require("./store-config")
// ...module.exports = withStoreConfig({
  // ...
  images: {
    domains: [
      // ...
      "<BUCKET_NAME>.s3.amazonaws.com",
    ],
  },
})

<BUCKET_NAME> represents the name of your bucket.


Run your storefront with yarn run dev to check if the new products you added are there and proceed to the next phase of your project.

Conclusion

This marks the end of this tutorial, hopefully, you were able to add a file service plugin to your Medusa store. To get the best of the tool, consider adding payment services, search and notifications services.