Building an Online Store with Saleor

Building an Online Store with Saleor

This post shows you how to quickly set up an e-commerce store with Saleor.io, a powerful GraphQL headless solution which helps business owners and development teams to build products faster in a shorter span of time.

This post shows you how to quickly set up an e-commerce store with Saleor.io, a powerful GraphQL headless solution.

In the era of modern web development, headless solutions become a popular way to build any kind of product. For example, Content Management systems, e-commerce solutions etc. In this article, we are going to see how to build an online store using headless e-commerce product Saleor.io, which is popular in the industry.

What is Saleor.io?

Saleor is a headless GraphQL ECommerce platform which helps business owners and development teams to build products faster in a shorter span of time. It provides us with all the modules we need to run an e-commerce store in a scalable way.

Saleor architecture

Saleor contains three important modules, including a backend solution and infrastructure, an admin dashboard for an e-commerce store, and an e-commerce client side solution.

A flowchart showinghow Saleor works.

Our store ( or client) communicates with backend through the Saleor SDK. At the same time, the admin dashboard communicates with the backend using a GraphQL API.

In this tutorial, we will see how to setup a Saleor backend and Admin dashboard for an e-commerce store. We will also see how to build a storefront (client) side for an e-commerce application.

Installation and setup

Note: to set up and run Saleor in a development environment, it’s best to use Docker.

We are going to use Docker for setting it up in our development environment.

git clone https://github.com/mirumee/saleor-platform.git --recursive --jobs 3
cd saleor-platform
docker-compose build

With the above command, we’ll build Docker images for us in our local machine.

docker-compose run --rm api python3 manage.py migrate
docker-compose run --rm api python3 manage.py collectstatic --noinput

Since the Saleor server is running in Python, it sets up the server and database migration for us.

//first command is optional
docker-compose run --rm api python3 manage.py populatedb 
docker-compose run --rm api python3 manage.py createsuperuser

After that, we populate our database with dummy data (this is optional), and then we create a super user for our admin dashboard.

Finally, to run the services, use this command:

docker-compose up

Now, if you visit the URL, you’ll see this:

http://localhost:3000/ – Client side

http://localhost:8000/graphql/ – GraphQL playground

http://localhost:9000/ – Admin Dashboard

Information about the store.

Our storefront.

Building a sticker store using Saleor

Now, we have the basic Saleor setup to build an online store. Let’s build a developer stickers store by customizing the Saleor storefront.

Devops.

Here are all the important modules/functionalities that we will be focusing on:

  • Listing Products based on category
  • Featured product
  • Search product
  • User – Login/Signup
  • Add to cart
  • Checkout product
  • Payment

To get the data from our GraphQL server, we need ApolloClient. This is because @saleor/sdk uses Apollo internally.

Let’s set up an Apollo Client in our React application.

npm install @saleor/sdk
import { SaleorProvider, useAuth } from "@saleor/sdk";

const config = { apiUrl: "http://localhost:8000/graphql/" };
const apolloConfig = {
  /* 
    Optional custom Apollo client config.
    Here you may append custom Apollo cache, links or the whole client. 
    You may also use import { createSaleorCache, createSaleorClient, createSaleorLinks } from "@saleor/sdk" to create semi-custom implementation of Apollo.
  */
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <SaleorProvider config={config} apolloConfig={apolloConfig}>
    <App />
  </SaleorProvider>,
  rootElement
);

const App = () => {
  const { authenticated, user, signIn } = useAuth();

  const handleSignIn = async () => {
    const { data, dataError } = await signIn("[email protected]", "admin");

    if (dataError) {
      /**
       * Unable to sign in.
       **/
    } else if (data) {
      /**
       * User signed in succesfully.
       **/
    }
  };

  if (authenticated && user) {
    return <span>Signed in as {user.firstName}</span>;
  } else {
    return <button onClick={handleSignIn}>Sign in</button>;
  }
};

Now, we need to build components and use the GraphQL Server to list and update the data to our server.

@saleor/sdk provides a lot of custom Hooks out of the box. It helps us to save lot of development time to build the store. A few of them are:

  • useAuth – Authentication hooks which handles authentication mechanism. it provides the logged in user info and check if the user is authentication etc.
  • useCart – it provides functionality to add product to cart and remove product from cart.
  • useSignOut – it sign out the user from the store.
  • useUserDetails – it returns the information about the logged in user.
  • useUserDetails – it provides functionality to checkout all the items in the cart.

There are lot of custom Hooks like this. I am just pointing out some of the important ones here. You can check all the Hooks in the @saleor/sdk.

SDK React.

Now, we are going to fetch the products and product category from the server. But, if you skipped the step of populating the database with dummy data on the installation, you may need to add Products and Categories to the database.

We can do that using our store admin dashboard. Go to Catalog => Product in the admin dashboard and add the products.

Catalog.

Do the same for Categories as well. This way, you can have Categories and Products to fetch from the server.

Once you add both of them, we can write GraphQL queries to fetch the product and categories.

query ProductsList {
    products(first: 5) {
      edges {
        node {
          id
          name
          pricing{
            onSale
            discount{
              gross{
                amount
              }
              currency
            }
          }
          description
          category{
            id
            name
          }
          images{
            id
            url
          }
        }
      }
    }
    categories(level: 0, first: 4) {
      edges {
        node {
          id
          name
          backgroundImage {
            url
          }
        }
      }
    }
  }

It fetches both products and categories from the server.

Product list.

You can use that data to list all the products and categories in our store.

import React, { useRef, useState } from "react";
import {
  ProductsList_categories,
  ProductsList_shop,
  ProductsList_shop_homepageCollection_backgroundImage,
} from "./gqlTypes/ProductsList";
import { structuredData } from "../../core/SEO/Homepage/structuredData";
// import noPhotoImg from "../../images/no-photo.svg";
import ProductItem from '../../components/product/ProductItem'
import Boundary from './boundary'
const Page = ({ loading, categories, products, backgroundImage, shop }) => {
  const [columnCount, setColumnCount] = useState(10);
  const categoriesExist = () => {
    return categories && categories.edges && categories.edges.length > 0;
  };
  const productListWrapper = useRef(null);
  return (
    <>
      <script className="structured-data-list" type="application/ld+json">
        {structuredData(shop)}
      </script>
      <main className="content">
        <section className="product-list-wrapper">
          <Boundary>
            <div
              className="product-list"
              ref={productListWrapper}
              style={{ gridTemplateColumns: `repeat(${columnCount}, 160px)` }}
            >
              {products.edges.map((product, index) => {
                return (
                  <ProductItem
                    foundOnBasket={false}
                    product={product.node}
                    key={`product-skeleton ${index}`}
                  />
                )
              })}
            </div>
          </Boundary>
        </section>
      </main>
    </>
  );
};
export default Page;

So far, we have the product and category listing functionalities. Now, we need to implement a way to add the product into a basket and add user login/signup functionalities.

saleor web-development graphql programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Software Developer vs Web Developer | Difference Web Developer & Software Developer

Software Developer vs Web Developer | Difference Web Developer & Software Developer | Software development and web development are normally used interchangeably. Although both include development, a software developer has different responsibilities from that of a web developer.

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.