- 5 min to read
How to build an e-commerce storefront with Next.js and Shopify
Shopify has a lot of themes you can choose from and customize to create your store. However, the customization options are limited. For a unique e-commerce experience, you may need to create your own frontend. It's where Headless Shopify comes in. Headless Shopify allows you to build the frontend separately from backend. You can keep the powerful features of Shopify like payment processing, built-in compliance, inventory, order management, and a checkout supporting different payment methods while building a unique frontend using the technology of your choice.
What is the Shopify Storefront API?
The Shopify Storefront API allows your custom frontend to talk with Shopify’s backend. You can make API calls to Shopify and access product data and other services like the checkout page.
Reading this article, you will learn how to build a Shopify storefront using the Storefront API and Next.js. By the end, you should be able to send GraphQL requests to Shopify and use the response data in your front end.
Let’s get started!
Creating a Shopify store
Navigate to Shopify Partners and create your Shopify Partner account (if you don't have one already). The account will allow you to create a store for development purposes at no cost.
Click Stores on the Shopify Partners dashboard to add a store. Ensure you select Development Store as the store type, then fill in the store details.
Once you create the store, you are ready to create a private app.
Creating a Shopify Private App
Create a private app by following the steps below:
- From your Shopify admin, click Settings > Apps and sales channels.
- Click Develop apps.
- Click Create an app.
- In the modal window, enter the App name.
- Click Create app.
Once you’ve created the app, follow these steps to configure the Storefront API.
- Navigate to the configuration tab and click Storefront API integration.
- Select all the checkboxes in the Storefront API access scopes. It permits you to fetch products.
- Click Save.
To get the access token:
- Click Install app on the app’s dashboard.
- In the modal, click Install app.
- Copy the access token from the API Credentials tab.
Copy the access token and the shop URL in the .env file.
The shop URL follows this format.
https://{store_name}.myshopify.com/api/2022-10/graphql.json
The last step of setting up Shopify is to add sample products to the store.
Creating a Next.js project
Start by running the following command in the terminal to create a Next.js project.
npx create-next-app@latest
This command should prompt you as follows:
√ What is your project named? ... nextjs-shopify
√ Would you like to use TypeScript with this project? ... No / Yes
√ Would you like to use ESLint with this project? ... No / Yes
Name the project shopify-store and select “No” for TypeScript and “Yes” for EsLint.
Now, run the app using the following command.
npm run dev
Querying the Storefront API
To make GraphQL requests, use graphql-request, a minimal client for sending GraphQL requests.
Run the following command on the terminal to install it.
npm install graphql-request
To fetch the products from Shopify and manage the cart, you’ll need queries that do the following:
- fetch all products
- fetch a single product
- add items to the cart
- update the cart
- retrieve the checkout URL
Let’s create these queries.
In the base folder of your app, create a new folder called utils and add a new file named shopify.js.
Fetching All Products from Shopify
Open the utils/shopify.js file in your editor and add the code which imports GraphQLClient and gql from graphql-request.
import { gql, GraphQLClient } from "graphql-request";
Assign the Storefront access token and the shop URL to a storefrontAccessToken and endpoint variable.
const storefrontAccessToken = process.env.STOREFRONTACCESSTOKEN;
const endpoint = process.env.SHOPURL
Add the following code to create a GraphQL client instance. You’ll use it to make requests.
Create a new function called getProducts and define the query for fetching products from Shopify.
You can now call the getProducts function to fetch products from Shopify. Next, you’ll create a function that fetches a single product by handle.
Fetch a product from Shopify
In utils/shopify.js, add a new function called getProduct that accepts a product ID as an argument.
export const getProduct = async (id) => {
};
Modify the function to include the query for fetching the product.
In getProduct, use the query in the GraphQL request and pass the ID as a variable.
Next, you’ll create a function that creates a cart and adds items to the cart.
Adding an item to the cart
In utils/shopify.js, add a new function named addToCart, that accepts a product ID and quantity as arguments.
Next, define the mutation for creating a cart.
This function creates a new cart and adds a product to it. Next, you’ll create a function that adds a product to an existing cart.
Updating the cart
Add a function named updateCart in utils/shopify.js and define the mutation for updating the cart.
This mutation is used to find the cart with the specified cart ID and update it with the item.
Modify the updateCart function to make the request as follows:
After creating or updating the cart, you’ll need to retrieve it
Retrieving the cart
In utils/shopify, add a function named retrieveCart and add a query for retrieving the cart.
This query uses the cart ID to query for IDs of the products in the cart and the total estimated cost. Add the following to the retrieveCart function to make the request.
Next, you’ll create a function that retrieves the checkout URL.
Retrieving the checkout URL
Add a function named retrieveCheckout that receives a cart ID as an argument in utils/shopify.js. Then, add the query for fetching the checkout URL from Shopify.
Add the following try/catch statement to make the request and return the checkout URL.
You have already created all the functions you’ll use to get products and manage the cart. The next step is to create the frontend, beginning with the products page.
Creating the products page
The products page displays all the products and their prices.
To get started, export the getServerSideProps function in pages/index.js and call the getProducts function from utils/shopify.js.
Because you’re rendering the ProductCard component for each product, you need to create it.
In the base folder, create a new folder called components and add the ProductCard/ProductCard.js file.
Add the following code that renders the product to this file.
Note that the product title links to a product details page that you’ll create in the next step.
For brevity, all the CSS files are in the GitHub repo.
Creating the product details page
Create products/[handle].js file in the pages folder. The file will fetch the product details by the ID passed in the URL query.
Start by exporting the getServerSideProps function in products/[id].js file and fetch the product by passing context.query.productid to the getProduct function.
The Product page uses a ProductDetails component, so create components/ProductDetails/ProductDetails.js file and add the following:
This component displays the product image, its title, and price. It also allows a user to specify the number of items they want to buy.
The “Add to Cart” button calls a function called handleAddToCart when clicked. Implement it in the ProductDetails component as follows.
If the quantity of items is greater than 0 but there is no cart in the session, this function should create a cart and add the item to it. If a cart does exist, it should update the cart with the item.
In the next section, you will list the cart items and the total then create a checkout button.
Creating the cart page
In the pages folder, create a file named cart.js and export a getServerSideProps function that calls the retrieveCart function from utils/shopify.js.
Call the getCheckoutUrl function to get the checkout URL of the cart.
In the Cart component, iterate over the cart items and render them. Additionally, display the total amount and the checkout button.
You now have a working cart!
What’s next?
So far, you have fetched products from Shopify, created a cart for users to add products to, and enabled checkout.
You can now add more functionalities to your store. For example, you may:
- add a function that increases or decreases the quantity of items in the cart,
- add a function for removing items from the cart,
- login users and add a buyer identity to each cart.
Find the queries and mutations to implement the above functionality and more in the Shopify GraphQL API documentation.
The sample code for the application created in this tutorial can be found in GitHub repository.