How I Built a Vue.js Ecommerce Store with a Node.js Backend
Noble Okechi
Posted on December 7, 2022
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.
Visit the Docs to learn more about our system requirements.
What is Medusa
Medusa is a set of commerce modules and tools that allow you to build rich, reliable, and performant commerce applications without reinventing core commerce logic. The modules can be customized and used to build advanced ecommerce stores, marketplaces, or any product that needs foundational commerce primitives. All modules are open-source and freely available on npm.
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:
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:
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><divclass="bg-purple-300 py-32 px-4 gap-y-20 justify-center items-center"><divclass="font-extrabold text-4xl text-center space-y-3"><divclass="">Join Our Wait List And Get</div><divclass="text-red-custom">Discount Up to 50%</div><divclass=""><divclass="py-1 flex relative max-w-xl mx-auto"><inputtype="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"><spanclass="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><divclass="bg-purple-800 py-32 PX-4"><divclass="max-w-6xl gap-6 mx-auto grid grid-cols-1 md:grid-cols-9"><divclass="md:col-span-3 py-3 space-y-4"><divclass="text-2xl font-bold text-gray-100">Noble's Shop</div><divclass="text-gray-300 w-60 pr-0">We sell only but quality and first grade Hoddies, Joggers, Shorts and lot more.</div></div><divclass="md:col-span-2 py-3 space-y-4"><divclass="text-2xl font-bold text-gray-100">Information</div><divclass="text-gray-300 w-60 space-y-2 pr-0"><divclass="">About Us</div><divclass="">More Search</div><divclass="">Online Order</div><divclass="">Support</div></div></div><divclass="md:col-span-2 py-3 space-y-4"><divclass="text-2xl font-bold text-gray-100">Our Services</div><divclass="text-gray-300 w-60 space-y-2 pr-0"><divclass="">Clothing</div><divclass="">Fashion</div><divclass="">Design</div><divclass="">Privacy</div></div></div><divclass="md:col-span-2 py-3 space-y-4"><divclass="text-2xl font-bold text-gray-100">Contact Us</div><divclass="text-gray-300 w-60 space-y-2 pr-0"><divclass="">+234 098-897-8888</div><divclass="">info@domain-name.com</div><divclass="">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><divclass="py-28"><divclass="max-w-6xl mx-auto py-4 space-y-5"><divclass="flex"><divclass="flex-grow text-4xl font-extrabold">Special Qualities For You</div></div><divclass="grid gap-20 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 px-3"><divv-for="(products, i) in fetchData":key="i"class="rounded-lg shadow-xl"style=""><router-link:to="{ name: 'single-product', params: { id: products.id }}"><divclass=" bg-white w-full flex justify-center items-center"><img:src="products.thumbnail"alt=""srcset=""></div><divclass="bg-purple-100 py-8 relative font-bold text-xl w-full flex flex-col justify-center px-6"><divclass="">{{products.title}}</div><divclass="">€{{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 loadedthis.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:
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:
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:
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:
<scriptsetup>
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:
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.jsfile, 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: