DEV Community

Cover image for Using Medusa as a JavaScript Ecommerce Framework
Aliyu Adeniji
Aliyu Adeniji

Posted on • Edited on • Originally published at adenijialiyu.hashnode.dev

Using Medusa as a JavaScript Ecommerce Framework

Javascript ecommerce framework: How to get started with Medusa

[adeniji aliyu olamilekan's photo

adeniji aliyu olamilekan's photo

](https://hashnode.com/@TheTechWriter)

adeniji aliyu olamilekan

·Jan 17, 2023·

12 min read

Introduction

Ecommerce simply means buying and selling goods and services over the internet. Ecommerce also involves the purchase of a wide range of product which include physical product, digital products and even services.

With the advancement of technology, ecommerce has become an ever-growing sector of the economy with a total value of about $6 trillion in a decade. By the year 2025, the sector is expected to grow to $8 trillion.

Javascript is a programming language that is commonly used to create interactive and dynamic dynamic web applications and ecommerce websites. Ecommerce websites can be built with javaScript to have features such as user account pages, product sliders, analytics and shopping carts. JavaScript is also used to retrieve, manage and update ecomerce websites.

In this article, you will learn about the applications of Javascript in ecommerce and how to get started with the Medusa Javascript headless ecommerce.

What is Medusa?

Medusa is an open source headless ecommerce platform that allows you to own, operate and grow a business on the internet. Medusa allows you to build a highly scalable and customizable ecommerce store that fits into your specific ecommerce needs.

It is built with JavaScript and TypeScript and uses Node.js on the server side. It also provides a headless backend engine for ecommerce websites.

Features of Ecommerce Websites

As ecommerce continues to grow, consumers who use ecommerce love to have seamless experiences when making purchases online. These are some of the features that you should have in your ecommerce store that will make you stand out.

A Mobile-Friendly Website

In the ecommerce space, the majority of ecommerce transactions is expected happen through mobile devices as time goes on, according to a research by insider intelligence. A well-optimized website for different screen sizes is a great feature that keeps customers glued to your website and makes the purchase a seamless experience for them.

A User-Friendly Website

The user interface of an ecommerce website should have a straightforward homepage, a well-placed search bar, and a prominent navigation bar. It should also be accessible to a wider range of users, including people with disabilities.

Advanced Search Options

Customers experience more accessibility and convenience in ecommerce stores when they’re able to make specific searches and get precise results immediately, customers can search for products easily by having access to typo tolerance search, auto complete search, and search suggestions; this helps to increase conversion rates of ecommerce stores.

Multiple Payment Gateways and Currencies

The presence of multiple payment gateways on an ecommerce website enables customers from around the world to make purchases using the payment methods accepted in their region. The availability of multiple currencies make it possible for customer in every part of the world to make purchases in their local currency.

Customizable Product Configuration

This allows ecommerce business stores to customize their product characteristics and different feature easily. For example, a sweatshirt can be configured such that customers can buy it in different colours and sizes.

Why You Should Use JavaScript for Your Ecommerce Site

JavaScript is a great tool that can be used to add extra functionalities to the ever growing needs of ecommerce websites. Product pages, content deliveries and several other ecommerce functionalities in ecommerce websites can be optimized using JavaScript.

Many ecommerce websites are JavaScript-based. This is due to the immense benefits it provides. Below are some of them.

1.Interactivity: JavaScript can be customized to provide a high level of interaction between the user and the application, so users of ecommerce websites built with JavaScript can see the changes they make to the website or their activity on the website in real time.

2.Speed and Accessibility: Due to its high-speed rendering capabilities, ecommerce websites can be made more accessible and faster by implementing lazy loading which allows partial loading of pages. Media resources such as videos and images can also be optimized to load only when they're visible on the screen, which leads to an optimized content delivery.

3.Versatility: Vanilla JavaScript is a versatile language that can be used for both frontend and backend development of ecommerce websites, making it easier for developers to work on projects that involve both aspects without having to learn multiple languages.

4.Scalability: Node.js uses a single thread to handle non-blocking input/output calls, which allows an evergrowing ecommerce application to accept concurrent connections with fewer resources

With Node.js, you can easily scale applications horizontally across multiple servers or vertically to increase its performance on a single server.

5.Cross-Platform Compatibility: JavaScript is platform-independent; it can run on any platform, including mobile devices. This makes it easier to create ecommerce websites that are compatible with multiple platforms and reduce the build time required to build ecommerce functionality for different web platforms

Features of Medusa Ecommerce

  • Multiple Region and Currency Support: Medusa ecommerce offers multiple regions to allow businesses to sell globally and define configurations specific to each region. You can also use different currencies for different regions with Medusa. The availability of multiple currencies in different regions allows users of all localities makes purchases in their own local currency. Flexible payment methods can be implemented by store owners depending on their choice and availability of the payment gateways in their region.

  • Plugins: With Medusa, you can integrate various plugins that allow the integration of various features to your store. Examples of plugins that can be integrated include payment plugins, customer services plugins, emailing plugins, and much more.

  • Advanced Search: Medusa allows you to integrate search engines such as Algolia or Meilisearch to your store. This allows users to be able to search for particular products with autocomplete and suggestions. Product updates are easily reflected in the stores when the official plugins of these search engines are integrated to the stores.

  • Bulk Import and Export: This feature enables store owners to easily import or export numerous records at a time, such records may include importing new products to their store or replacing and deleting selected products from their store.

  • Customer groups: Customer groups allow store owners to group customers into different clusters that allow them to monitor customers’ activities and to take business decisions such as promotions and giveaways.

Medusa Architecture

Medusa has three components which are:

Image description

  • The Medusa Server:

    This part handles the API and processes the requests. It is responsible for managing and organizing the data and functionality of the store, such as products, orders, and customer information.

  • The Admin Dashboard:

    This allows handling of the administrative services of the store and allows you to communicate with the backend server. The admin dashboard also allows you to manage products, orders, customers, and settings.

  • The Storefront:

    It acts as the store's frontend and is the only area of your online store that customers can view. The storefront shows all the contents of your store, including your products, promotions, product pages, and descriptions that enable your customers to make a purchase with your ecommerce store.

How to Create a JavaScript Ecommerce Store with Medusa

Prerequisites

Because Medusa is built on top of Node.js you need to install Node.js on your computer before you can get started with it. Make sure you have a Node.js version greater than 14; to confirm your version of Node, run the command node --version.

You can install both directly from their website.

Medusa Server Setup

To create a Medusa server, start by installing the Medusa CLI using the command below:

npm install @medusajs/medusa-cli -g
Enter fullscreen mode Exit fullscreen mode

Run the next command to create a fresh Medusa installation in a fresh directory:

medusa new my-new-server --seed
Enter fullscreen mode Exit fullscreen mode

Change the directory to your newly created server with the following command to start the server:

cd my-new-server

medusa develop
Enter fullscreen mode Exit fullscreen mode

You can test whether the Medusa server works well in your local server by going to the URL:

localhost:9000/store/products

Image description

As you can see, the server has been set up. You will get a response like this using a JSON viewing tool.

Adding Plugins to Medusa

Medusa store can be customized to add a search engine to your server.

Meilisearch is an open source search engine that can be integrated into ecommerce stores and provides fast and reliable search results for commerce websites.

Learn more on how to install Meilisearch here.

To integrate Meilisearch into your server, you should install Meilisearch plugin in your server using the following command in your server directory to install Meilisearch:

npm install medusa-plugin-meilisearch
Enter fullscreen mode Exit fullscreen mode

After the successful installation of the plugin, add the following variables to the .env file of your server directory.

MEILISEARCH_HOST=<YOUR_MEILISEARCH_HOST>

MEILISEARCH_API_KEY=<YOUR_MASTER_KEY>
Enter fullscreen mode Exit fullscreen mode

The <YOUR_MEILISEARCH_HOST> is the host of your Meilisearch engine and the local host is http://127.0.0.1:7700.

The <YOUR_MASTER_KEY> is any kind of string of letters that you choose to use as your master key. Check Meilisearch’s documentation on how to retrieve a Master key.

Add the following code snippet to the plugins variable in your medusa-config.js file in order to fully configure your search plugin:


const plugins = [
  {
    resolve: `medusa-plugin-meilisearch`,

    options: {
      // config object passed when creating an instance of the MeiliSearch client

      config: {
        host: process.env.MEILISEARCH_HOST,

        apiKey: process.env.MEILISEARCH_API_KEY,
      },

      settings: {
        // index name

        products: {
          // MeiliSearch's setting options to be set on a particular index

          searchableAttributes: ["title", "description", "variant_sku"],

          displayedAttributes: [
            "title",
            "description",
            "variant_sku",
            "thumbnail",
            "handle",
          ],
        },
      },
    },
  },
];
Enter fullscreen mode Exit fullscreen mode

The settings can be configured according to your needs.

Searchable attributes are those attributes whose values are searched in the store for matching query words.

Displayed attributes are the attributes whose fields are displayed in the search results.

How to Integrate Stripe as a Payment Option

Stripe is an ecommerce payment processing platform that allows businesses to receive payments for their services; it also allows the management of funds by businesses. Stripe provides a range of APIs that make it easy to integrate Stripe into ecommerce websites and make payments a seamless experience. Stripe also provides invoice services to businesses.

To integrate Stripe into your ecommerce website, follow the following steps.

To use Stripe as a payment gateway in your ecommerce store, you need the secret and publishable keys which can be gotten by creating a Stripe account.

pk_test_******************************************

sk_test_******************************************

The next step is to install the Stripe plugin into your project. Go to the root directory of your server and run the command below to install the plugin:

js
npm install medusa-payment-stripe
Enter fullscreen mode Exit fullscreen mode

Once the installation is complete, add the configuration below to the plugins array in your medusa-config.js file:

js
const plugins = [
  `medusa-fulfillment-manual`,

  {
    resolve: `medusa-payment-stripe`,
    options: {
      api_key: process.env.STRIPE_API_KEY,
      webhook_secret: process.env.STRIPE_WEBHOOK_SECRET,
    },
  },
];
Enter fullscreen mode Exit fullscreen mode

Please note that the webhook_secret will only be available for use in the production environment, so we are making use of the api_key only in the development environment.

Installing the Medusa Admin dashboard

Medusa Admin dashboard built on JavaScript provides a user-friendly interface that allows store owners to manage their online stores, store owners can manage orders, customers, logistics, and analytics using the admin server.

JavaScript is also used to validate user inputs in forms, which ensures that correct and valid information is used by customers when making changes to their accounts. Javascript is also used to manage the data generated from ecommerce storefronts and to make decisions by store owners.

To get an admin dashboard on Medusa ecommerce, you can clone the Admin GitHub repository by running the next command:

js
git clone <https://github.com/medusajs/admin> my-store-admin
Enter fullscreen mode Exit fullscreen mode

This will download the repository to your machine and make it available, the next step is to navigate to the location of your admin panel by running this command:

cd my-store-admin
Enter fullscreen mode Exit fullscreen mode

Then, you should install npm dependencies by running the following command:

npm install
Enter fullscreen mode Exit fullscreen mode

Once the Admin dashboard is successfully installed, use the command below to start your admin server, which will automatically open at port: 7000.

npm run start
Enter fullscreen mode Exit fullscreen mode

Your admin dashboard is now successfully built and running. The admin panel should look like the image below.

Image description

Log in to your admin panel using admin@medusa-test.com as your email and supersecret as your password.

How to Enable Stripe in the Admin Panel

The next step is to add Stripe as a payment option in a region in your admin dashboard. Follow the steps below:

  1. Navigate to settings in your admin dashboard.

  2. Select the regions option.

  3. Select the region you want to edit.

  4. Click on the three dots and select edit region details from the options displayed.

  5. Select Stripe from the payment providers menu.

Image description

Getting Started with Next.js Storefront

Medusa Next.js storefront is a React-based JavaScript framework that allows you to build fast, user-friendly and SEO-optmized ecommerce websites. Nextjs storefront provides a scalable and customizable storefront for ecommerce websites.

Create a new Next project running the command below:

npx create-next-app -e <https://github.com/medusajs/nextjs-starter-medusa> my-new-storefront
Enter fullscreen mode Exit fullscreen mode

Change the directory to the newly created storefront and rename the .env.template to be able to use the environment variables as shown below:

cd my-new-storefront
Enter fullscreen mode Exit fullscreen mode
mv .env.template .env.local
Enter fullscreen mode Exit fullscreen mode

Add the server URL to the .env.local file as shown in order for the storefront to be able to link back to the server while running:

NEXT_PUBLIC_MEDUSA_BACKEND_URL=http://localhost:9000
Enter fullscreen mode Exit fullscreen mode

Then, run the command below to start your storefront:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Your server will start running at the port localhost:8000.

Adding Stripe to the Storefront

The final step to integrate Stripe is to add Stripe’s publishable key to your storefront.

Go to the .env.local file in the root of your storefront file, and add the publishable key as shown below:

NEXT_PUBLIC_STRIPE_KEY=pk_test_******************************************
Enter fullscreen mode Exit fullscreen mode

Adding Meilisearch to the Storefront

After creating a working storefront, you must create an API key in order to be able to make searches on your storefront, run the following command in a new terminal when your Meilisearch instance is running:

curl \\
  -X POST '<MEILISEARCH_HOST>/keys' \\
  -H 'Content-Type: application/json' \\
  -H 'Authorization: Bearer <MEILISEARCH_MASTER_KEY>' \\
  --data-binary '{
    "description": "Search products",
    "actions": ["search"],
    "indexes": ["products"],
    "expiresAt": "2024-01-01T00:00:00Z"
  }'
Enter fullscreen mode Exit fullscreen mode

The next step is to enable the search feature in store.config.json file as shown below:

js
{
  "features": {
    "search": true
  }
}
Enter fullscreen mode Exit fullscreen mode

The final step to enable Meilisearch in your storefront is to add the environment variables to your .env.local file. Make sure you replace <YOUR_MEILISEARCH_HOST> with your MeiliSearch host and <YOUR_API_KEY> with the API key you created:

NEXT_PUBLIC_SEARCH_ENDPOINT=<YOUR_MEILISEARCH_HOST>
NEXT_PUBLIC_SEARCH_API_KEY=<YOUR_API_KEY>
NEXT_PUBLIC_SEARCH_INDEX_NAME=products
Enter fullscreen mode Exit fullscreen mode

Restart your server and storefront to update the new settings. To confirm if your integration is working, you can send a POST to /store/products/search. The endpoint accepts a q body parameter that returns a search result that matches the query.

Image description

Image description

Image description

Image description

This is an example of an electronic commerce platform.

Conclusion

Ecommerce is a way of life that many businesses and service providers are embracing and benefiting from.

In this article, we looked at those features and provided a brief overview of how to get started building on Medusa. We also discussed some of the applications of JavaScript in ecommerce.

To learn more about different ways of using Medusa for your ecommerce business, kindly read through Medusa’s official documentation here.

Should you have any issues or questions related to Medusa, then feel free to reach out to the Medusa team via Discord.

Share this

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.