Table of contents
- What is Vue.js
- What is Medusa
- Prerequisites
- Create a Server with Medusa Commerce Engine
- Medusa Admin Installation
- Create a New Vue.js Project
- Tailwind CSS Installation
- Integrate Vue.js Ecommerce Storefront with Medusa
- Creating Components for Your Vue.js Project
- Creating Vue.js Router File for Routing Pages
- Create Storefront Pages
- Change Vue.js Port
- Test the Storefront
- What’s Next?
Ecommerce is no small undertaking. Aside from building a great customer experience on the frontend, you’ll also need to have the right setup to handle all cart, customer and order data, product information, etc…
In this tutorial, you’ll get a sneak peek into how it can be done!
In this tutorial, you’ll get set up with the necessary prerequisites for a great ecommerce experience. Vue.js is a great choice for a frontend framework because it’s open source, it has a component-based architecture, and it is reactive.
For the backend, you’ll learn how to use Medusa, an open source Node.js commerce engine that ships with all necessary ecommerce functionality including an easily navigatable admin system.
The full code for this Vue.js project is located in this GitHub repo. Below is a quick sneak peek of the final result.
What is Vue.js
Vue.js is an open source progressive JavaScript framework. It can be used to build a variety of types of apps, including websites, mobile apps, or desktop apps. This can be done by using Vue.js along with other platforms like Electron or Ionic.
Vue.js has been rising in popularity since it was first released due to its many advantages. It is easy to learn and use, with concise documentation and a smooth learning curve. It also has a tiny size, a reactive system, and a component-based, reusable architecture.
What is Medusa
Medusa is the #1 open source, Node.js commerce platform on GitHub. Its composable and headless architecture allows it to be incorporated with any tech stack to build cross-platform ecommerce stores, ranging from web to android and iOS applications.
Medusa allows developers to build scalable and maintainable ecommerce stores. It ships with many advanced ecommerce features such as an admin store dashboard, product configurations, manual orders, multi-currency support, and much more. Likewise, it easily integrates with different payment, CMS, and shipping options.
Please star if you like the tool 🌟
Prerequisites
Before you start, be sure you have Node.js version 14 or above.
Create a Server with Medusa Commerce Engine
To set up the Medusa server on your local machine, follow the steps outlined in the sections below.
Install Medusa CLI Tool
Medusa CLI can be installed using npm
or yarn
, but this tutorial uses npm
. Run the following command to install the Medusa CLI:
npm install @medusajs/medusa-cli -g
Create a New Medusa Store Server
To create a new Medusa store server, run the command below:
medusa new my-medusa-store --seed
Note: my-medusa-store
represents the project name; you can change yours to your preferred project name.
If you created a new Medusa project successfully, you should get a result similar to the screenshot below.
Test Your Medusa Server
To test your Medusa server, change to the newly created directory and run the develop
command using Medusa’s CLI:
cd my-medusa-store
medusa develop
You can test it by sending a request to localhost:9000/store/products/
which lists the available products in your store.
Medusa Admin Installation
To set up your Medusa Admin, follow the steps below.
- Clone the Medusa Admin repository:
git clone <https://github.com/medusajs/admin> medusa-admin
cd medusa-admin
- Run the command below to install all necessary dependencies:
npm install
- Test it:
npm start
By default, Medusa Admin runs on port 7000
. You can go to localhost:7000
on your browser to access your admin page.
Since you included the --seed
option while installing the Medusa server, a dummy admin user has been created. The email is admin@medusa-test.com
, and the password is supersecret
.
With the Medusa Admin, you can create new products and collections for your store. You can also edit, unpublish, duplicate and delete products from the admin.
You can visit the User Guide to learn more about Medusa Admin.
Create a New Vue.js Project
The next thing is to create and set up a new Vue.js project for the ecommerce project. You can run this command to set up a new Vue.js project:
npm init vue@latest
This command will install and execute create-vue, the official Vue project scaffolding tool. You will be presented with prompts for a number of optional features such as TypeScript and testing support.
Ensure you choose the same option as the ones in the above screenshot.
Once the project is created, use the following commands to install the necessary dependencies:
cd vuejs-ecommerce
npm install
Tailwind CSS Installation
Tailwind CSS is a CSS framework that allows you to effortlessly style your ecommerce storefront. In this tutorial, you’ll use Tailwind CSS in your Vue.js ecommerce storefront.
In the vuejs-ecommerce
directory, run the following command to install Tailwind CSS:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
The above command will generate both the tailwind.config.js
and postcss.config.js
files in your Vue.js project.
Configure Your Template Paths
In your tailwind.config.js
file, replace the content
array with the following snippet:
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx,vue}",
],
Add the Tailwind Directives to your CSS
Go to src/assets/main.css
and replace the entire code with the snippet below:
@tailwind base;
@tailwind components;
@tailwind utilities;
The
base
layer handles things like reset rules or default styles applied to plain HTML elements.The
components
layer handles class-based styles that you want to be able to override with utilities.The
utilities
layer handles small, single-purpose classes that should always take precedence over any other styles.
You can visit Tailwind CSS documentation to learn more.
Integrate Vue.js Ecommerce Storefront with Medusa
In this section, you’ll prepare to integrate the Vue.js ecommerce storefront with the Medusa server to interact with APIs later on.
Create a Base URL Environment Variable
The baseURL
environment variable is the URL of your Medusa server. Create a .env
file in the vuejs-ecommerce
directory with the following content:
VITE_baseUrl=http://localhost:9000
Note: If for any reason, you changed the default port number of your Medusa Server, you must change the 9000
to your port number here.
Install Axios in the Vue.js Project
You’ll use Axios to send requests to your Medusa server. You can install Axios by running the following command:
npm i axios
Now that Axios is installed, the next step is integrating Medusa API into your project.
Creating Components for Your Vue.js Project
In this section, you will create components such as Header
, Footer
, and Products
components. These components will be used on different pages of your storefront.
In some components images are used to implement a better design for the storefront. You can find all images used for this project in the GitHub repository.
Page Header Component
Create the file src/components/PageHeader.vue
and add the following code to it:
<template>
<div>
<div class="fixed z-50 bg-white topNav w-full top-0 p-3 md:bg-opacity-0">
<div class="max-w-6xl relative flex mx-auto flex-col md:flex-row">
<a href="" class="md:hidden absolute top-1 right-14">
<div class="relative">
<img src="/src/images/icon.png" class="bottom-1 cursor-pointer relative">
<div class="absolute px-1 bg-red-500 -top-1 -right-1 rounded-full border-2 border-white text-white" id="cart2" style="font-size: 10px"></div>
</div>
</a>
<div class="absolute h-10 flex justify-center bars items-center w-10 text-white right-1 -top-2 rounded-lg shadow-lg md:hidden cursor-pointer border-2 border-white bg-red-500">
<i class="fa fa-bars"></i>
</div>
<div class="flex-grow font-bold text-lg">
<router-link :to="{ name: 'home'}" >
<span class="">Noble's Shop</span>
</router-link>
</div>
<div class="menu hidden md:flex flex-col md:flex-row mt-5 md:mt-0 gap-16">
<div class="flex flex-col md:flex-row gap-12 capitalize">
<div class="">
<router-link :to="{ name: 'home'}" >
<span class="text-red-400 font-bold border-b border-red-400">home</span>
</router-link>
</div>
<div class="">
<router-link :to="{ name: 'products'}" >
<span class="">products</span>
</router-link>
</div>
</div>
<div class="flex gap-12">
<a href="#" class="hidden md:block">
<div class="relative">
<img src="/src/images/icon.png" class="bottom-1 cursor-pointer relative">
<div v-if="productId.length > 0" class="absolute px-1 bg-red-500 -top-1 -right-1 rounded-full border-2 border-white text-white" id="cart" style="font-size: 10px">{{productId.length}}</div>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:{
productId:Array
}
}
</script>
The above code block covers the header page of this project. It includes the page routes, website name, and shopping cart icon.
This component will be added later in src/App.vue
of this project to add a header on every page of this storefront.
Footer Component
Create the file src/components/FooterComponent.vue
with the following content:
<template>
<div>
<div class="bg-purple-300 py-32 px-4 gap-y-20 justify-center items-center">
<div class="font-extrabold text-4xl text-center space-y-3">
<div class="">Join Our Wait List And Get</div>
<div class="text-red-custom">Discount Up to 50%</div>
<div class="">
<div class="py-1 flex relative max-w-xl mx-auto">
<input type="text" placeholder="Enter Your Email Here" class="text-sm border w-full pr-52 focus:ring-red-400 focus:border-red-400 relative px-5 placeholder-gray-400 py-6 -right-1 border-red-400 rounded-lg flex-grow">
<span class="bg-btn-color absolute text-base -right-1 uppercase rounded-lg z-10 text-white px-16 py-6 bg-opacity-25" style="top: 5px">
sign in
</span>
</div>
</div>
</div>
</div>
<div class="bg-purple-800 py-32 PX-4">
<div class="max-w-6xl gap-6 mx-auto grid grid-cols-1 md:grid-cols-9">
<div class="md:col-span-3 py-3 space-y-4">
<div class="text-2xl font-bold text-gray-100">Noble's Shop</div>
<div class="text-gray-300 w-60 pr-0">We sell only but quality and first grade Hoddies, Joggers, Shorts and lot more.</div>
</div>
<div class="md:col-span-2 py-3 space-y-4">
<div class="text-2xl font-bold text-gray-100">Information</div>
<div class="text-gray-300 w-60 space-y-2 pr-0">
<div class="">About Us</div>
<div class="">More Search</div>
<div class="">Online Order</div>
<div class="">Support</div>
</div>
</div>
<div class="md:col-span-2 py-3 space-y-4">
<div class="text-2xl font-bold text-gray-100">Our Services</div>
<div class="text-gray-300 w-60 space-y-2 pr-0">
<div class="">Clothing</div>
<div class="">Fashion</div>
<div class="">Design</div>
<div class="">Privacy</div>
</div>
</div>
<div class="md:col-span-2 py-3 space-y-4">
<div class="text-2xl font-bold text-gray-100">Contact Us</div>
<div class="text-gray-300 w-60 space-y-2 pr-0">
<div class="">+234 098-897-8888</div>
<div class="">info@domain-name.com</div>
<div class="">Terms & Condition</div>
</div>
</div>
</div>
</div>
</div>
</template>
In the above component, you covered everything about the footer page of this ecommerce app. You’ll use it later across your pages where you want to add a footer.
Products Component
Create the file src/components/Products.vue
with the following content:
<template>
<div>
<div class="py-28">
<div class="max-w-6xl mx-auto py-4 space-y-5">
<div class="flex">
<div class="flex-grow text-4xl font-extrabold">Special Qualities For You</div>
</div>
<div class="grid gap-20 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 px-3">
<div v-for="(products, i) in fetchData" :key="i" class="rounded-lg shadow-xl" style="">
<router-link :to="{ name: 'single-product', params: { id: products.id }}">
<div class=" bg-white w-full flex justify-center items-center">
<img :src="products.thumbnail" alt="" srcset="">
</div>
<div class="bg-purple-100 py-8 relative font-bold text-xl w-full flex flex-col justify-center px-6">
<div class="">{{ products.title}}</div>
<div class="">
€ {{ products.variants[0].prices[0].amount / 100 }}
</div>
</div>
</router-link>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
import { RouterLink } from 'vue-router';
export default ({
data(){
return{
fetchData:[]
}
},
mounted(){
// calling the fetchProducts method when the page has loaded
this.fetchProducts();
},
methods:{
fetchProducts(){
axios.get(`${import.meta.env.VITE_baseUrl}/store/products`)
.then((data) => {
this.fetchData = data.data.products
}).catch(err => console.log(err.products));
}
}
})
</script>
The product component is where the products are fetched using Medusa’s APIs. fetchProducts
method is used to fetch products from the Medusa Server. Notice how you use the baseURL
defined in the .env
file.
In addition, the Vue router is being used to route each selected product to a single product page which you’ll add later.
Creating Vue.js Router File for Routing Pages
The next thing to do is to create a router file for routing our pages. By default, a route file is always generated when creating the vue.js project. Find the src/router/index.js
file and replace the code inside with the below content:
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import SingleProductView from '../views/SingleProductView.vue'
import ProductView from '../views/ProductView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/products',
name: 'products',
component: ProductView
},
{
path: '/single-product/:id',
name: 'single-product',
component: SingleProductView
}
]
})
export default router
In the above component, you specified all your routes, including the route path, name, and components. The routes you added are for the homepage, products page, and single product page.
Create Storefront Pages
In this section, you’ll create pages for your storefront. Before you start creating these pages, go to src/App.vue
and replace the code with the following:
<script setup>
import { RouterLink, RouterView } from 'vue-router'
import PageHeader from './components/PageHeader.vue'
</script>
<template>
<header>
<page-header :productId="products" />
</header>
<RouterView @addp="addP($event)" />
<div class="fixed top-12 bg-green-600 text-white z-50 border text-md uppercase shadow-lg py-1 px-4 rounded-lg transistion-all duration-700" :class="notify">item added successfully</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
products:[],
notify:'-right-64',
cartId:'',
product_variant_id:null
}
},
mounted(){
this.checkCartID()
},
methods:{
getCartID(){
axios.post(`${import.meta.env.VITE_baseUrl}/store/carts`).then((res) => {
localStorage.cart_id = res.data.cart.id;
});
},
checkCartID(){
this.cartId = localStorage.cart_id;
if (!this.cartId) {
this.getCartID();
}
},
addP(data){
this.cartId = localStorage.cart_id;
axios.post(`${import.meta.env.VITE_baseUrl}/store/carts/${this.cartId}/line-items`, {
variant_id: data,
quantity: 1,
})
.then(({ data }) => {
this.products.push(data)
localStorage.cart = this.products
this.notify = 'right-3'
var inter = setInterval(() =>{
this.notify='-right-64'
clearInterval(inter)
},1000)
})
}
}
}
</script>
Here, you import the header component so that it appears on all pages.
You also add some methods related to the cart. The checkCartID
method checks on page load if there’s a cart ID in the local storage, and if so calls the getCartID
method. The getCartID
method is used to fetch cart and its items from the Medusa server.
The addP
method is used to add products to your store cart. It will be called later on the Single Product page.
You can learn more about Medusa carts in the documentation.
Homepage View
Create the file src/views/HomeView.vue
with the following content:
<script setup>
import PageHeader from '../components/PageHeader.vue'
import Products from '../components/Products.vue'
import FooterComponent from '../components/FooterComponent.vue'
</script>
<template>
<main>
<div class="bg-purple-300 w-full">
<div class="" style="height: 92vh">
<div class="max-w-6xl mx-auto h-full flex items-center">
<div class="grid gap-1 px-3 grid-cols-1 mt-8 md:grid-cols-5">
<div class="md:col-span-2 order-2 flex flex-col justify-center space-y-12">
<div class="space-y-5">
<div class="font-extrabold w-full text-6xl">
Nothing But Qualities
</div>
<div class="text-lg leading-7 max-w-md">
We sell quality Hoddies, Joggers, Shorts and lot more
</div>
</div>
<div>
<router-link :to="{ name: 'products'}">
<span class='w-fit cursor-pointer transistion-all duration-300 hover:text-purple-400 text-white px-3 py-3 bg-gradient-to-r from-purple-500 to-pink-500 rounded flex justify-center items-center'>
Explore More
</span>
</router-link>
</div>
</div>
<div class="md:col-span-3 flex justify-center md:order-2">
<img src="/src/images/hoddie.png" class="bottom-1 relative h-11/12" style="">
</div>
</div>
</div>
</div>
<div class="flex justify-center bg-purple-300 py-4 pb-10 w-full">
<div class="h-14 rounded-2xl relative" style="border: 1px solid black;padding:3px 6px 3px">
<div class="bg-black rounded-full relative top-10" style="padding: 3px"></div>
</div>
</div>
</div>
<products/>
<footer-component/>
</main>
</template>
<script>
export default {
mounted(){
this.handlePageScroll()
},
methods:{
handlePageScroll(){
window.scrollTo(0, this.scrollposition);
this.scrollposition = window.pageYOffset;
}
}
}
</script>
You import the Products
and FooterComponent
components inside this file and display them on the Homepage.
Products Page View
Create the file src/views/ProductView.vue
with the following content:
<script setup>
import PageHeader from '../components/PageHeader.vue'
import Products from '../components/Products.vue'
import FooterComponent from '../components/FooterComponent.vue'
</script>
<template>
<main>
<products/>
<footer-component/>
</main>
</template>
You also import the Products
and FooterComponent
components inside this file to display them in the Products listing page.
Single Product Page
Create the file src/views/SingleProductView.vue
with the following content:
<script setup>
import FooterComponent from '../components/FooterComponent.vue'
</script>
<template>
<main ref="addProd">
<div class='py-20 px-4'>
<div class='text-white max-w-6xl mx-auto py-2'>
<div class='grid md:grid-cols-2 gap-20 grid-cols-1'>
<div class=''>
<div class="relative">
<img :src="imgArr[currentImg]" alt="no image" />
<div class="absolute overflow-x-scroll w-full bottom-0 right-0 p-4 flex flex-nowrap gap-4">
<div v-for="(er,i) in imgArr.length" :key="i" class="flex w-full flex-nowrap gap-4 rounded-lg">
<div @click="currentImg = i" :title="imgArr[i]" class="w-16 h-24 flex-none">
<div class="h-full w-full rounded-lg cursor-pointer shadow-lg border overflow-hidden">
<img :src="imgArr[i]" alt="" class="h-full w-full">
</div>
</div>
</div>
</div>
</div>
</div>
<div class=''>
<div class='flex md:flex-col flex-col space-y-7 justify-center'>
<div class='text-black space-y-3'>
<h2 class='font-bold text-xl text-black'>{{product.title}}</h2>
<p class='text-sm'>{{product.description}}</p>
</div>
<div class='space-y-3'>
<div class='font-bold text-md text-black'>Select Size</div>
<div class='flex flex-row flex-wrap gap-4'>
<div v-for="(size,i) in sizes" :key="i" class="">
<div @click="currentSize = size ; currentPrice = priceList[i] ; variants_id = product.variants[i].id" :class="currentSize == size ? 'border-purple-300 bg-purple-100':'border-gray-100' " contenteditable="false" class='border-2 rounded-md cursor-pointer flex justify-center py-3 px-5'>
<span class=' text-black text-sm'>{{size}}</span>
</div>
</div>
</div>
</div>
<div>
<div class='flex flex-col space-y-3'>
<div>
<span class='text-gray-700 text-2xl font-san'>€ {{ currentPrice }}</span>
</div>
<div @click="addProduct()" class='bg-gray-900 cursor-pointer text-white w-full text-sm font-semibold py-3 flex justify-center cursor pointer hover:bg-white hover:border hover:border-gray-900 hover:text-black '>
ADD TO CART
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer-component/>
</main>
</template>
<script>
import axios from 'axios'
export default {
activated() {
window.scrollTo(0, 0);
},
data(){
return{
currentImg : 0,
imgArr:[],
productData:[],
product:[],
productId:'',
sizes:[],
currentSize:'S',
priceList:[],
currentPrice: '',
variants_id: 0
}
},
mounted(){
window.scrollTo(0, 0);
},
beforeMount(){
this.productId = this.$route.params.id
axios.get(`${import.meta.env.VITE_baseUrl}/store/products/${this.productId}`)
.then((productData) => {
this.product = productData.data.product;
console.log(this.product);
this.product.images.forEach(data => {
this.imgArr.push(data.url)
});
this.currentPrice = this.product.variants[0].prices[0].amount / 100
this.variants_id = this.product.variants[0].id
this.product.variants.forEach(data => {
this.sizes.push(data.title)
this.priceList.push(data.prices[0].amount / 100)
});
}).catch(err => console.log(err));
},
methods:{
addProduct(){
this.$emit('addP',this.variants_id)
}
}
}
</script>
In the above code block, you are fetching a single product from the Medusa server using its id. Then, you display the product’s information including its price, size, and description.
When the Add to Cart button is clicked, the addProduct
method is executed. This method calls the addP
method defined in src/App.vue
passing it the selected variant ID.
Change Vue.js Port
In the vite.config.js
file, add this code snippet inside the object parameter passed todefineConfig
:
server: {
port:8000
},
In the above code block, you change the port of the Vue.js ecommerce storefront to 8000
. This allows you to avoid cors
issues when sending requests to the Medusa server.
Test the Storefront
You can now test your Vue.js ecommerce storefront with the following steps:
- Run the Medusa server:
medusa develop
- Run the Vue.js app:
npm run dev
When you open the storefront on localhost:8000
, you’ll see the following home page:
If you scroll down or click on the Products item in the navigation bar, you’ll see products populated from your Medusa server.
Try clicking on any of the products, a new page will open showing the products details.
You can add the product to the cart by clicking the “Add to Cart” button.
What’s Next?
In this tutorial, you learned how to create a Vue.js Ecommerce storefront with the help of Medusa. This storefront only implements the product listing and add-to-cart functionality, but there’s much more to add to your storefront.
Check out the following documentation pages for help on how to move forward:
Add a checkout page.
Install Stripe plugin to process payments.
Add advanced search functionality with MeiliSearch.
Should you have any issues or questions related to Medusa, then feel free to reach out to the Medusa team via Discord