Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Medusa: Node.js ecommerce platform for 11ty
Medusa profile imageQuadri Sheriff
Quadri Sheriff forMedusa

Posted on • Edited on • Originally published atmedusajs.com

     

Medusa: Node.js ecommerce platform for 11ty

In this tutorial, you will learn how to build a modern e-commerce storefront with Medusa and 11ty. You will create our store’s backend using Medusa's headless commerce engine and admin panel, and the store’s frontend with the 11ty framework and tailwind CSS.

Medusa is the open source Shopify alternative providing a headless commerce solution that is focused on maximizing developer flexibility.11ty is a very flexible simple static site generators used for building modern websites.

In this tutorial, you will learn how to:

  1. Set up Medusa's backend server
  2. Install DigitalOcean spaces for easier file management
  3. Set up Medusa's admin panel for easier management of your online store
  4. Build a simple storefront with 11ty and TailwindCSS

Below is avideo of what we will be building

Prerequisites
To follow through this tutorial, make sure to have:

  • Nodejs and NPM installed on your local machine. You can follow the instructionsin this link to fully install Nodejs and npm on your local computer.
  • Git installed locally with a GitHub account. Follow the instructionshere to install git, and create a GitHub accounthere.
  • DigitalOcean account. Create a DigitalOcean accounthere.

Why Medusa?

  • Open source - Medusa is an open source software that can be used as a commerce backend for your webshop and with a large support community behind it which you can accesshere.
  • Headless architecture - Medusa’s headless architecture makes it easy to build with any type of frontend (e.g. 11ty) and integrate with your favorite CMS, payment, fulfillment solutions etc.
  • Multi-market support - Medusa natively supports multiple currencies and allows you to set use local shipping and payment providers for a globale setup.
  • Fully customizable - Our extendible architecture makes it easy to customize for any type of advanced use case and makes it easy to build in custom logic and integrations.

Medusa backend installation and setup

The first step in this tutorial will be to set up the Medusa server and admin panel. Medusa provides 3 core components for managing your commerce projects - a headless commerce engine that exposes REST APIs for your frontend consumption, a customizable frontend, and an admin panel for managing your store.

In this project, we will be making use of the headless commerce engine and admin panel only since we will be building the storefront with 11ty. To set up the backend server, first install the Medusa CLI.

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

Then create a new project with the installed CLI.

medusa new <my-medusa-store> --seed
Enter fullscreen modeExit fullscreen mode

Change to the preferred name of your project. Navigate to the generated folder, and create a new user.

cd <my-medusa-store>medusa user -e <some@email.com> -p <some_password>
Enter fullscreen modeExit fullscreen mode

Change<some@email.com> to your preferred email, and to your preferred password.

Finally, start up the created server.

medusa develop
Enter fullscreen modeExit fullscreen mode

The server can be accessed athttp://localhost:9000.

Set up DigitalOcean Spaces for Image Uploads
After installation the Medusa server, the next step will be to set up a DigitalOcean space for storing our uploaded images. To do that:

  • Open your DigitalOcean account. Navigate to Spaces. Create a new Space with the default settings.
  • Select the created space, and clickManage Keys.
    manage-keys

  • ClickGenerate New Key.
    generate-keys

  • Add the Key name and save it.
    key-name

A key ID and secret key will be automatically generated, copy the keys to a safe place. Now, navigate back to the medusa project folder, and install themedusa-file-spaces package.

npm install medusa-file-spaces
Enter fullscreen modeExit fullscreen mode

Then open your medusa-config.js file, and add the following code sample to the plugins section.

{    resolve: `medusa-file-spaces`,    options: {        spaces_url: "https://test.fra1.digitaloceanspaces.com",        bucket: "test",        endpoint: "fra1.digitaloceanspaces.com",        access_key_id: "YOUR-ACCESS-KEY",        secret_access_key: "YOUR-SECRET-KEY",    },},
Enter fullscreen modeExit fullscreen mode

Changespaes_url to the URL of your created DigitalOcean space, changebucket to the name of the space, changeaccess_key_id to the generated key ID, and change thesecret_access_key to the generated secret key.

Set up and Install the Medusa Admin Panel
Medusa provides an admin panel that makes it easy to configure and manage our store. To set up the admin panel you should first clone the admin repository from GitHub.

git clone https://github.com/medusajs/admin <medusa-admin>
Enter fullscreen modeExit fullscreen mode

Change to your preferred folder name. Then navigate to the admin folder

cd <medusa-admin>
Enter fullscreen modeExit fullscreen mode

Install all the required packages

npm install
Enter fullscreen modeExit fullscreen mode

And finally, start the admin panel

npm start
Enter fullscreen modeExit fullscreen mode

The admin panel will load up athttp://localhost:7000/.

admin-panel

Log in with your server’s user mail and password to access the admin dashboard.

log-in

Add Products to the store
Now that we have fully set up the Medusa server and admin panel, the next step will be to add products to our store. We will be doing this through the admin panel, as the admin panel makes it much easier compared to sending API requests to the server directly.

To add a product to the store:

  1. Select products on your side menu and clickNew product on the right-hand side of the window.
    select-product

  2. Add your product information and clickSave to register the new product.
    product-info

  3. ClickPublish on the next step to publish the new product.
    publish

Make sure to add at least 3 products to your store, this is required to complete the frontend setup for this particular tutorial. For each product, make sure to add:

  • A thumbnail image
  • 4 product images
  • Product Name
  • Product description
  • Handle (the handle should be in slug format i.e., t-shirts, face-caps, etc.)

Create product collections
After adding the products to your store, the next step will be to group them into collections. For this tutorial, we will be using:

  • Weekly sales collection
  • Bestsellers collection

To create a collection:

  1. Select collections under products in the sidebar menu. ClickNew collection on the top right-hand side to create the new collection.
    new-collection

  2. Add the collection title and handle, then clickSave.
    save

To add a product to a collection,

  1. Click the Product on the Product page to reveal the Product Information page.
    product-info

  2. Click the collection dropdown and select a collection to add the product to that collection.
    dropdown

  3. ClickSave to save your changes. Make sure to add each of your products to a collection.

11ty storefront installation and setup

Now that our Medusa setup is complete with products added, the next step in our tutorial will be to create a storefront for our store with the 11ty frontend framework. 11ty is a simple static site generator with zero configs by default, it is a flexible framework and allows for the usage of multiple templating languages like Nunjucks, Liquid, Javascript, markdown, etc. at once.

To install 11ty, create a new folder with the preferred name of your storefront. Navigate to the folder and initialize the folder with npm.

npm init -y
Enter fullscreen modeExit fullscreen mode

A package.json file will be added to the folder. Then install 11ty into the folder with the following command.

npm install --save-dev @11ty/eleventy
Enter fullscreen modeExit fullscreen mode

Confirm your installation with the following command.

npx @11ty/eleventy
Enter fullscreen modeExit fullscreen mode

You should get a response similar to this if your installation is successful.

Wrote 0 files in 0.03 seconds (v0.12.1)
Enter fullscreen modeExit fullscreen mode

Now that we have completed our 11ty setup, the next step will be to install TailwindCSS into the frontend. TailwindCSS is a utility-first css framework used for building modern websites. Visithttps://tailwindcss.com/ to learn more about the css framework.

To add TailwindCSS to 11ty; first, install TailwindCSS and its dependencies.

npm install tailwindcss postcss-cli autoprefixer
Enter fullscreen modeExit fullscreen mode

Then generate your tailwind configuration file with the following command.

npx tailwind init
Enter fullscreen modeExit fullscreen mode

Create a new file namedpostcss.config.js and add the following to the file.

// postcss.config.jsmodule.exports = {  plugins: {    tailwindcss: {},    autoprefixer: {},  }}
Enter fullscreen modeExit fullscreen mode

Create a css folder, and add a file named index.css to the folder. Then add the following code snippet to the c*ss/index.css* file.

@tailwind base;@tailwind components;@tailwind utilities;
Enter fullscreen modeExit fullscreen mode

Finally, update your package.json file with the following code snippet.

 "scripts": {   "dev": "postcss css/index.css -o _site/css/index.css && eleventy --serve --quiet",   "build": "postcss css/index.css -o _site/css/index.css" },
Enter fullscreen modeExit fullscreen mode

To start the 11ty server, runnpm run dev. The server will open up athttp://localhost:8080/.

Create the storefront file structure
11ty is a very flexible framework, and ships with zero configs. It is up to us to set up our project however we want. Add an src folder to your root folder, this is the main folder where our files will be stored. Also, add a_includes and a_helper folder to the src folder. Components files will be stored in thesrc/_includes folder, while data files will be stored in thesrc/_helpers folder.

Add a.eleventy.js file to your root folder, and add the following code snippets to the .eleventy.js.

const HtmlMin = require('html-minifier');const ErrorOverlay = require('eleventy-plugin-error-overlay'); module.exports = eleventyConfig => { eleventyConfig.setTemplateFormats(['md']); eleventyConfig.addPlugin(ErrorOverlay); eleventyConfig.addTransform('htmlmin', (content, outputPath) => {   if (outputPath.endsWith('.html')) {     const minified = HtmlMin.minify(content, {       useShortDoctype: true,       removeComments: true,       collapseWhitespace: true,     });     return minified;   }   return content; }); return {   dir: {   input: "src",   output: "_site",   includes: "_includes",   data: "_helpers",   },   jsDataFileSuffix: '.data', };};
Enter fullscreen modeExit fullscreen mode

The .eleventy.js file is our main 11ty configuration file. The code sample simply notifies 11ty of where our data files and includes files are stored, and where to store the output data. We also added ahtml-minifier plugin andeleventy-plugin-error-overlay to the project.

Finally, install the two plugins with the following command.

npm install html-minifier eleventy-plugin-error-overlay
Enter fullscreen modeExit fullscreen mode

After completing the setup, your file structure should look like this:

file-structure

Create the Storefront’s layout
The next step is to create the storefront’s layout. We will majorly be using Nunjucks as our templating engine of choice.

First add a header.njk and a footer.njk file to your_includes folder. Add the following code samples to the_includes/header.njk file,

<header>  <div     >    <nav>      <a        href="/"               >Products</a      >      <svg               viewBox="0 0 24 24"        fill="none"        xmlns="http://www.w3.org/2000/svg"      >        <path          d="M3 3H5L5.4 5M7 13H17L21 5H5.4M7 13L5.4 5M7 13L4.70711 15.2929C4.07714 15.9229 4.52331 17 5.41421 17H17M17 17C15.8954 17 15 17.8954 15 19C15 20.1046 15.8954 21 17 21C18.1046 21 19 20.1046 19 19C19 17.8954 18.1046 17 17 17ZM9 19C9 20.1046 8.10457 21 7 21C5.89543 21 5 20.1046 5 19C5 17.8954 5.89543 17 7 17C8.10457 17 9 17.8954 9 19Z"          stroke="currentColor"          stroke-width="2"          stroke-linecap="round"          stroke-linejoin="round"        />      </svg>    </nav>    <a      href="/"         >      <svg        width="38"        height="40"        viewBox="0 0 38 40"        fill="none"        xmlns="http://www.w3.org/2000/svg"      >        <path          d="M32.4865 6.48972L23.4254 1.28128C20.4607 -0.427092 16.8279 -0.427092 13.8631 1.28128L4.76024 6.48972C1.83728 8.19809 0 11.3648 0 14.7399V25.1984C0 28.6152 1.83728 31.7402 4.76024 33.4486L13.8214 38.6987C16.7861 40.4071 20.4189 40.4071 23.3836 38.6987L32.4448 33.4486C35.4095 31.7402 37.205 28.6152 37.205 25.1984V14.7399C37.2885 11.3648 35.4512 8.19809 32.4865 6.48972ZM18.6234 29.2819C13.4873 29.2819 9.31169 25.1151 9.31169 19.99C9.31169 14.8649 13.4873 10.6981 18.6234 10.6981C23.7594 10.6981 27.9768 14.8649 27.9768 19.99C27.9768 25.1151 23.8012 29.2819 18.6234 29.2819Z"          fill="#56FBB1"        /></svg>    </a>  </div></header>
Enter fullscreen modeExit fullscreen mode

Then, add the following to the_includes/footer.njk file.

<footer>  <div     >    <div>      <a        href="/"               >Create Return</a      >      <a        href="/"               >FAQ</a      >      <a        href="/"               >Terms and Shipping</a      >    </div>    <div>      <a        href="/"               >Discord</a      >      <a        href="/"               >GitHub</a      >      <a        href="/"               >LinkedIn</a      >    </div>  </div></footer>
Enter fullscreen modeExit fullscreen mode

Finally, add a layout.njk file to your _incudes folder. Add the following code sample to the_includes/layout.njk file.

    <html>      <head>        <title>medusa storefront</title>        <link rel="stylesheet" href="css/index.css" />      </head>      <div>{% include "header.njk" %}</div>      <div>        <body>          <div>            {{ content | safe }}          </div>        </body>      </div>      <div>{% include "footer.njk" %}</div>    </html>
Enter fullscreen modeExit fullscreen mode

In this code, we basically imports our css stylesheet, and also wrapped the page content with the createdheader.njk andfooter.njk file. To use the layout on a page, simple add the layout.njk file to the page’s frontmatter.

Import Medusa server’s content to the storefront
Now that we have created our store’s layout, the next step will be to import products from the Medusa server to the storefront. To do this, we will have to import the product data as an 11ty global data variable.
Add a file name products.js to your _helpers folder, and add the following code samples to the_helper/products.js file.

const { default: axios } = require('axios'); module.exports = async () => { try {   const res = await axios.get('http://localhost:9000/store/products');   return res.data.products; } catch (error) {   console.error(error); }};
Enter fullscreen modeExit fullscreen mode

This code makes a get request to the Medusa server and returns the response to be stored as an 11ty global data. Visit thislink to access a list of API endpoints provided by Medusa.
The returned data can be accessed anywhere in the storefront. Finally, install axios since we will be making our api calls with axios.

npm install axios
Enter fullscreen modeExit fullscreen mode

Create the Storefront’s Homepage
The storefront homepage will comprise 2 sections, a hero section and a products section for displaying our products.
Add a hero.njk file and a product.njk file to the_includes folder. Then, add the following code sample to the_includes/hero.njk file.

    <div>      <div>        <div                          >          <img                       src="https://user-images.githubusercontent.com/59125401/144878845-da9d252a-abfb-4fa1-8fca-fa46c7b103b1.png"            alt="hero photo"          />        </div>        <div                 >          <div>            <h2>              Get Free <span>Merch</span>            </h2>            <p>              Contribute to Medusa and get free merch as a token of our appreciation.            </p>            <div>              <a                               href="#"                >Get Started</a              >            </div>          </div>        </div>      </div>    </div>
Enter fullscreen modeExit fullscreen mode

Add the following code sample to the_includes/product.njk file.

    <div     >    {%- for product in products -%}      <a  key="{{ product.id }}"              href="/{{ product.handle }}.html"             >        <img          src="{{ product.thumbnail }}"          alt="{{ product.id }}"                 />        <h3>{{ product.title }}</h3>        <h3>${{ product.variants.0.prices.0.amount }}</h3>      </a>    {%- endfor -%}    </div>
Enter fullscreen modeExit fullscreen mode

In this code, we basically displayed part of our product details using the liquid templating engine. Add anindex.md file to yoursrc folder and add the following code snippet to the**src/index.md** file.

    ---    title: "Home"    layout: layout.njk    ---    {% include hero.njk %}       {% include product.njk %}
Enter fullscreen modeExit fullscreen mode

In this code, we basically imported the hero.liquid file and product.liquid file using the include variable. We also implemented our created layout by adding it as a front matter to the file. When you visithttp://localhost:8080/, you should see a page similar to this:

home

Create Single Product views
The last step will be to create our single product views, 11ty provides a pagination variable that allows us to create multiple files from a single template. Create a new file in the src folder named product.md. Add the following code samples to thesrc/product.md file.

    ---    layout: layout.njk    pagination:      data: products      size: 1      alias: product    permalink: "/{{ product.handle }}.html"    title: { { product.title } }    ---    <div         >      <div>        <img          src="{{ product.thumbnail }}"          alt="{{ product.id }}"                 />      </div>      <div>        <div>          <img            src="{{ product.images.0.url }}"            alt="{{ product.id }}"                     />        </div>        <div>          <img            src="{{ product.images.1.url }}"            alt="{{ product.id }}"                     />        </div>      </div>      <div>        <div                 >          <img            src="{{ product.images.2.url }}"            alt="{{ product.id }}"                     />        </div>        <div                 >          <img            src="{{ product.images.3.url }}"                     />        </div>      </div>    </div>    <div         >      <div             >        <h1                 >          {{ product.title }}        </h1>        <div>          <p>{{ product.description }}</p>          <div>            <p>Product collection -</p>            <p>{{ product.collection.title }}</p>          </div>          <div>            <p>Price -</p>            <p>${{ product.variants.0.prices.0.amount }}</p>          </div>         </div>        <form>          <div>            <h1>Quantity -</h1>            <input type="number" name="quantity" value="1" min="0" max="10" />          </div>          <h1>Variants</h1>          <div>          {%- for variant in product.variants -%}            <label for="{{ variant.id }}">              {{ variant.title }}              <span></span>            </label>            <input name="{{ variantId }}" type="radio" value="{{ variant.id }}">          {%- endfor -%}          </div>          <button            type="submit"                     >            Add to cart          </button>        </form>      </div>    </div>
Enter fullscreen modeExit fullscreen mode

In this code, we simply iterated over the product data and create a page with each product. The link to a product is also generated with the handle using the permalink variable. To visit a product page, simply click the product in your homepage, you should see a page similar to this:

product

Conclusion

In this tutorial, we created a storefront with Medusa and 11ty. You can access the code for this project in this GitHub repository -https://github.com/Quadrisheriff/medusa-storefront

For more info about Medusa, please visit theirdocumentation or stay updated on theirDiscord where the community is ready to support you.

For info about 11ty, please visit theirwebpage or get help in theirDiscord.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
sudiptaadhikaryjoy profile image
Sudipta Adhikary Joy
CSE student
  • Email
  • Location
    Dhaka, Bangladesh
  • Education
    Lovely Professiona University, India
  • Pronouns
    he/his
  • Work
    Frontend Web Developer @Akij Venture Ltd
  • Joined

Can i change any of the frontend framework for storefront?

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Open source composable commerce for devs.

Check out our GitHub repository to join our community, contribute to Medusa, and learn about our roadmap.

More fromMedusa

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp