Nextjs Shopify Headless Storefront Setup

Author

Reads 694

Stylish boutique store interior featuring an elegant collection of luxury bags displayed on tiled walls.
Credit: pexels.com, Stylish boutique store interior featuring an elegant collection of luxury bags displayed on tiled walls.

To set up a Nextjs Shopify headless storefront, you'll need to create a Shopify store and connect it to your Nextjs application. This can be done using Shopify's API and the Shopify Buy SDK.

First, create a Shopify store and set up a development store. This will provide you with a test environment to work in.

Next, install the Shopify Buy SDK in your Nextjs project using npm or yarn. This will allow you to interact with the Shopify API and retrieve data from your store.

To connect your Nextjs application to your Shopify store, you'll need to obtain a private app in your Shopify admin panel. This will give you a private app API key and API secret that you can use to authenticate your requests.

A unique perspective: Api Routes Nextjs

Getting Started

To get started with Next.js and Shopify, you'll need to have the following prerequisites: npm and node.js installed on your PC, a text editor, a terminal, and a Netlify account.

You'll also need to clone a starter project that contains a simple Next.js app with basic CSS styles. This can be done by typing a command in your terminal. After cloning the project, run the following commands to install the required dependencies and start-up your development server.

Recommended read: Next.js

Next.js Project Setup

Credit: youtube.com, Next js Tutorial for Beginners | Nextjs 13 (App Router) with TypeScript

To set up a Next.js project, you'll need to have npm and node.js installed on your PC, a text editor, a terminal, and a Netlify account.

First, you can create a new Next.js project by running the command `npx create-next-app@latest` in your terminal. This will prompt you to name your project, and you can choose to use TypeScript and ESLint or not.

If you prefer a starter project with some things already set up, you can clone the starter branch using the command provided in the tutorial. This will give you a simple Next.js app with basic CSS styles and the required dependencies installed.

To complete the setup, update the `_app.js` file with the code that imports the client variable and returns the results inside a props object. This will pre-render your data before the page loads.

To get started, quickly download the latest Next.js TypeScript starter and answer the questions as prompted. You'll need to update the `tsconfig.json` file and the `globals.css` file with the provided code.

Worth a look: Nextjs Starter

Credit: youtube.com, Master Next JS in easy way

Here are the prerequisites you'll need to follow this tutorial:

  • npm and node.js installed on your PC
  • A text editor
  • Terminal
  • A Netlify account

To run your app, use the command `npm run dev` after creating or cloning your project. This will start your development server, and you can access your app by opening `http://localhost:3000` in your browser.

Recommended read: Shopify App Nextjs

A Quick Introduction

Shopify is an online selling platform with a monthly subscription.

It's a cloud-based software as a service shopping cart solution that lets business owners set up their ecommerce websites and sell products with ease.

Using Shopify's APIs, developers can create custom ecommerce websites, which is also known as headless commerce.

Headless commerce separates your backend infrastructure from the frontend consumer interactions without design or development restrictions.

This means you can focus on building a seamless user experience without worrying about the technical details.

To get started, you'll need to create a directory called product in your app directory, then another directory inside there called [id].

In the [id] directory, create a page.tsx file to create a dynamic page for your product.

You might like: Next Js 14 Ecommerce

Storefront API Setup

Credit: youtube.com, Build a Next.js E-commerce Storefront with Typescript, Tailwindcss, TanStack Query, and Shopify API.

To set up the Storefront API, you'll need to create a private app in your Shopify store. This involves setting permissions for the Storefront API in the configuration tab, specifically for storefront access. You'll also need to install the API credentials and copy the generated access token.

The Storefront API allows your custom frontend to communicate with Shopify's backend, enabling you to access product data and other services like the checkout page. To make GraphQL requests, you can use graphql-request, a minimal client for sending GraphQL requests. This requires installing it via npm install graphql-request.

To make the most of the Storefront API, you'll need to configure your Shopify-buy package to get data for your Shopify store easily. This involves creating a file to configure the Shopify-buy package, specifically a shopifyStore.js file in the utils folder at the root of your project. You'll need to set up your domain and storefrontAccessToken in this file.

Configure Client

Credit: youtube.com, How to Use the Shopify API and Make GraphQL Requests

To configure the client for your Shopify Storefront API, you'll need to create a file to set up the Shopify-buy package. This file will help you get data for your Shopify store easily.

First, create a utils folder at the root of your project. Inside this folder, create a shopifyStore.js file.

You'll need to import and configure the Shopify-buy package in this file. This is done by creating a client variable using Shopify's buildClient API. You'll pass a config object to this API, where you'll set your domain and storefrontAccessToken.

To get your storefrontAccessToken and domain, follow these steps:

1. Log in to your Shopify store admin dashboard.

2. Click on the Apps link on the sidebar.

3. Click on Manage private apps at the bottom of the page.

4. Select your app, scroll to the bottom of the page and copy the storefront access token.

5. Copy your domain from your Shopify admin URL.

Once you have these values, create a .env.local file at the root of your project and add the following:

```

STOREFRONT_ACCESS_TOKEN=your_access_token

DOMAIN=your_domain_url

```

Replace the texts with your actual Storefront access token and Domain URL.

On a similar theme: Creating Shop Page Next Js

Storefront API Setup

Credit: youtube.com, How to create Shopify Storefront API access token [2025 Easy Guide]

To set up the Storefront API, you'll need to create a Shopify custom app. This involves creating a development store if you don't already have one, and setting up a private app in the Shopify admin dashboard.

First, create a custom app in your Shopify store. You can do this by going to the Shopify admin dashboard, clicking on Apps, and then clicking on Manage private apps.

Next, set up the necessary permissions for the app to access your Shopify inventory. This includes setting the Storefront API permission in the configuration tab.

To do this, go to the configuration tab, select Storefront API, and choose the following permissions:

  • Read products
  • Read products by ID
  • Read collections
  • Read product variants
  • Read product images

You'll also need to set up the API Credentials tab, where you can install the app and generate an access token.

The access token is used to authenticate your app and grant it access to your Shopify store's data. You can find this token in the API Credentials tab after installing the app.

Credit: youtube.com, How To Use Shopify's Storefront API | Easy Tutorial

Here's a summary of the permissions you need to set up:

Product Management

To manage products in a Next.js Shopify app, you'll need to create a function called `getProduct` that fetches a product by its ID. This function should be added to the `utils/shopify.js` file and use a GraphQL query to fetch the product.

You'll also need to create a dynamic page for each product, which can be done by creating a `product` directory in the app directory, and inside that, a `[id]` directory with a `page.tsx` file. This will allow you to link to a product's page using its ID.

To display product information on the page, you can use the `getProduct` function to fetch the product data, and then use the `params` prop in your component to access the product ID from the URL.

For another approach, see: Why Use Next Js

Fetching All Products

To fetch all products from Shopify, you need to create a GraphQL client in the utils/shopify.js file. Import the GraphQLClient and gql from graphql-request.

Expand your knowledge: Next Js Graphql

A businessman working in an online store packing shoes in a cardboard box.
Credit: pexels.com, A businessman working in an online store packing shoes in a cardboard box.

You can then assign the Storefront access token and the shop URL to a storefrontAccessToken and endpoint variable using environment variables. The Storefront access token is typically stored as an environment variable named STOREFRONTACCESSTOKEN, and the shop URL is stored as an environment variable named SHOPURL.

To create a new function called getProducts, define the query for fetching products from Shopify. This query will use the API_VERSION, which can be obtained from the GraphiQL playground, and the shop name, which can be obtained from the shop URL.

Here's a summary of the required environment variables:

  • STOREFRONTACCESSTOKEN: the Storefront access token
  • SHOPURL: the shop URL
  • API_VERSION: the API version, which can be obtained from the GraphiQL playground

You can then call the getProducts function to fetch products from Shopify. This function will return a list of products, which you can then use to render the products on your page.

Fetch a Product

You can fetch a product from Shopify using a function called getProduct. This function accepts a product ID as an argument and uses a GraphQL query to fetch the product details.

Readers also liked: Next Js Fetch Data

Eco-friendly shop interior featuring wooden shelves and bulk food storage for zero waste shopping.
Credit: pexels.com, Eco-friendly shop interior featuring wooden shelves and bulk food storage for zero waste shopping.

The getProduct function is defined in the utils/shopify.js file and can be called to fetch a product by its ID. The function takes the ID as an argument and returns the product details.

Here's an example of how to use the getProduct function to fetch a product:

```javascript

export const getProduct = async (id) => {

// GraphQL query to fetch product details

const query = gql`

query Product($id: ID!) {

product(id: $id) {

title

description

price

images {

altText

url

}

}

}

`;

// Execute the query and return the product details

const response = await client.request(query, { id });

return response.product;

};

```

The getProduct function uses a GraphQL query to fetch the product details, including the title, description, price, and images. The query takes the product ID as a variable and returns the product details as a JSON object.

You can call the getProduct function by passing the product ID as an argument, like this:

```javascript

const product = await getProduct('gid://shopify/Product/1234567890');

console.log(product);

```

This would fetch the product with the ID 'gid://shopify/Product/1234567890' and log the product details to the console.

A different take: Query in Nextjs

Cart and Checkout

Credit: youtube.com, Add a Shopping Cart & Checkout to a Next.js App with Snipcart

In the world of e-commerce, a seamless cart and checkout experience is crucial for customer satisfaction and conversion rates. To achieve this, we need to create a robust cart system that allows users to easily add, update, and retrieve their cart contents.

To start, we add a new function named addToCart in utils/shopify.js, which accepts a product ID and quantity as arguments. This function creates a new cart and adds a product to it. We also create a function named updateCart, which updates the cart with the specified item.

When it comes to retrieving the cart, we add a function named retrieveCart in utils/shopify.js, which uses the cart ID to query for IDs of the products in the cart and the total estimated cost. We also create a function named retrieveCheckout, which receives a cart ID as an argument and returns the checkout URL.

In the cart page, we iterate over the cart items and render them, displaying the total amount and the checkout button. This is achieved by calling the getCheckoutUrl function to get the checkout URL of the cart, and then rendering the cart items and total amount in the Cart component.

Add to Cart

Credit: youtube.com, Ecommerce Website | Add to Cart | Delete from Cart | HTML, CSS & JavaScript

To add a product to your cart, you need to create a new function in utils/shopify.js that accepts a product ID and quantity as arguments.

This function is called addToCart, and it's where the magic happens.

The mutation for creating a cart is defined within this function, which creates a new cart and adds a product to it.

Next, you'll create a function that adds a product to an existing cart, but that's a story for another time.

The addToCart function is a crucial part of the cart and checkout process, and it's already been created, along with all the functions you'll use to get products and manage the cart.

Now it's time to create the frontend, starting with the products page.

Take a look at this: Html Shopping Cart

Retrieving the Cart

To retrieve the cart, you need to add a function named retrieveCart in utils/shopify.js. This function will make a query to Shopify to fetch the cart items and total estimated cost.

Credit: youtube.com, Simple Shopping Cart - Stripe Checkout Demonstration

The retrieveCart function uses the cart ID to query for IDs of the products in the cart and the total estimated cost. To make the request, you'll need to add the following code to the retrieveCart function.

You'll also need to handle any errors that might occur during the request. To do this, you'll add a try/catch statement to the retrieveCart function.

In the retrieveCart function, you'll use the cart ID to query for the cart items and total estimated cost. This will allow you to display the cart items and total cost on the cart page.

To make the request, you'll need to use the GraphQL query for retrieving the cart. This query will fetch the cart items and total estimated cost based on the cart ID.

Once you've implemented the retrieveCart function, you'll be able to display the cart items and total cost on the cart page. This will provide a seamless shopping experience for your users.

Page Creation

Credit: youtube.com, How I Create Modern E-Commerce Stores with Next.js

To create the pages for your Shopify store, you'll need to start by exporting the getServerSideProps function in the pages/index.js file and call the getProducts function from utils/shopify.js. This will fetch the product data and render the ProductCard component for each product.

In the components folder, create a new folder called components and add the ProductCard/ProductCard.js file. This file will render the product to the page, with the product title linking to a product details page that you'll create next.

To create the product details page, export the getServerSideProps function in the products/[id].js file and fetch the product by passing context.query.productid to the getProduct function. This component will display the product image, title, and price, and allow users to specify the number of items they want to buy.

Generating Critical Pages

To generate critical pages, you need to define the paths to the pages that will be statically generated at build time. This can be done in the getStaticPaths() function, which returns an array of paths to be generated.

Credit: youtube.com, Why is THIS the PERFECT Landing Page?

You can specify the paths to be generated by looping through all your products and telling Next.js to statically generate only the path to the first product at build time. This is what we did in our [id].js file, where we defined the path to the first product's data.

By setting the fallback value to false, we're telling Next.js not to generate the data for other products whose paths weren't defined in the getStaticPaths() function. This means that if we try to access the details page of any of those products, we'll get a 404 page.

However, if we set the fallback value to true or blocking, Next.js will generate the path for that product, serve the page to the user, and cache it automatically on Netlify's CDN. This way, subsequent requests to the same path will serve the cached page as if it were part of the pages statically generated at build time.

This approach benefits our site by decreasing build times, especially when we have a large number of products. We can generate the paths for only the first product at build time, and then generate the paths for other products on demand when a user requests them.

Creating the Products Page

Businessman packing products and managing an online store from his desk with a laptop.
Credit: pexels.com, Businessman packing products and managing an online store from his desk with a laptop.

To get started, export the getServerSideProps function in pages/index.js and call the getProducts function from utils/shopify.js.

You'll need to create a new folder called components in the base folder and add a new file called ProductCard.js.

Add the following code to render the product in this file.

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.

In the ProductCard.js file, you'll render the product to this file, using the ProductCard component for each product.

Here's a step-by-step guide to creating the products page:

  • Create a new folder called components in the base folder.
  • Add a new file called ProductCard.js to the components folder.
  • Export the getServerSideProps function in pages/index.js and call the getProducts function from utils/shopify.js.

Cart Page Creation

Creating the cart page is a crucial step in building a functional e-commerce site. To start, you need to create a file named cart.js in the pages folder and export a getServerSideProps function that calls the retrieveCart function from utils/shopify.js.

The getServerSideProps function is essential for fetching data on the server-side, allowing you to render dynamic content. You'll also need to call the getCheckoutUrl function to get the checkout URL of the cart.

Credit: youtube.com, Creating A Checkout Page That Sells More | Outperform Any Online Store

Once you have the cart items, you can iterate over them and render them in the Cart component. Don't forget to display the total amount and the checkout button, which will be essential for the user's checkout experience.

With these steps, you'll have a working cart page that allows users to view their items and proceed to checkout.

Display More Data

Displaying more data on your Shopify page is a great way to enhance the user experience. You can update your GraphQL query to fetch additional fields such as description, featuredImage, handle, price, tags, and title.

To do this, you'll need to modify your GraphQL query to include these fields. For example, you can update your query to fetch the product description, featured image, handle, price, tags, and title like this:

Next, you'll need to update your JSX to display this new data. You can do this by adding the necessary HTML elements to render the data. For instance, you can add a paragraph element to display the product description and an image element to display the featured image.

Discover more: Nextjs Image

Hands typing on a laptop showing an e-commerce website in a modern office setting.
Credit: pexels.com, Hands typing on a laptop showing an e-commerce website in a modern office setting.

In your page component, you can use the params prop to access the product ID from the URL. This will allow you to fetch the correct product data from the Shopify API. You can then use this data to populate the HTML elements on your page.

To make your code more readable, you can create a formatPrice util function to handle the price formatting. This will help keep your code organized and make it easier to maintain.

Here are the types you'll need to update to accommodate the new data:

By following these steps, you can display more data on your Shopify page and enhance the user experience.

Create Shared Components

To create shared components, start by creating an src folder and inside that folder, create a components folder.

Add four files to the directory: Header.js, Footer.js, Hero.js, and Cart.js. The hero section of your project should contain a simple title and a paragraph explaining your application's details.

Credit: youtube.com, Full React Tutorial #12 - Reusing Components

Wrap your entire application with the ShopProvider component to make context data available throughout the project. This is done by adding a ShopProvider component.

Create a FeaturedProducts.js file in the components folder and add code to it. The FeaturedProducts component receives products as props from the index.js file where it's rendered.

Iterate over the products and display them, destructuring the addItemToCheckout and openCart functions from ShopContext.

Features and Setup

This Next.js Shopify project comes with a robust set of features that make it perfect for ecommerce websites. The project uses Next.js App Router & Turborepo, which ensures lightning-fast performance and SEO optimization.

The project also includes React Server Components (RSCs), Suspense, and Streaming, making it a great choice for complex ecommerce applications. Server Actions and Dynamic OG Images are also supported, allowing for flexible and customizable content rendering.

To get started with the project, you can clone the starter branch and run the required commands to install dependencies and start the development server. The project is set up with a simple Next.js app, basic CSS styles, and the JavaScript Shopify-buy SDK, making it easy to integrate ecommerce functionality.

Worth a look: Nextjs Server Only

GraphiQL App Setup

A woman relaxes with her laptop browsing online shopping websites from her cozy home.
Credit: pexels.com, A woman relaxes with her laptop browsing online shopping websites from her cozy home.

To set up the GraphiQL app, start by installing the GraphQL API app. Go to the specified page to install it.

You'll know you're in the GraphiQL playground when you see a query to start with. This initial query should be run and will display something like a list of products.

To query for products, create a ProductsQuery. Start off simple by getting just the product titles. You'll need to provide an argument to products(), which is typically either first or last.

Features

With Next.js App Router & Turborepo, you get a solid foundation for building fast and scalable applications. This combo provides a robust framework for managing complex codebases.

The app is built with React Server Components (RSCs), Suspense, and Streaming, which enables lightning-fast search and filtering capabilities. This is thanks to the ⚡ symbol, indicating a key feature.

Server Actions are designed to work seamlessly with the app, allowing for efficient data processing. You can also expect perfect performance and SEO with this setup.

Credit: youtube.com, Setup | Review and opt-in to new features after update

The app comes with a range of features that make development easier, including AI Vector Search and AI Image captioning. These features are particularly useful for building complex applications.

TypeScript is used throughout the app, with extremely strict enforcement to ensure code quality. This is reflected in the 🔎 symbol, indicating a focus on precision.

Other notable features include Draft Mode, A/B Tests, and TailwindCSS, Shadcn UI, which make it easy to design and test your application. Analytics are also integrated, allowing you to track performance and make data-driven decisions.

Additional reading: Next Js Ai

State Management Setup

To set up state management, create a context folder at the root of your project and add a shopContext.js file inside it.

Create a Shopify-buy configuration and import it into your shopContext.js file.

The shopContext.js file should contain a state to store initial values and a createCheckout function that creates an empty checkout instance.

This checkout instance will be updated later when you call addItemsToCheckout.

By setting up state management in this way, you'll be able to manage your application's state effectively.

Everything works as expected, and clicking on each product will take you to that product's page.

Consider reading: Next Js Strike Checkout

Final Steps

Credit: youtube.com, Headless Shopify Ecommerce using Nextjs #shopify #nextjs #ecommercewebsite

Now that you've set up your Next.js Shopify store, it's time to take it to the next level. You've already fetched products from Shopify, created a cart for users to add products to, and enabled checkout.

You can now focus on adding more functionalities to your store. For example, you can add a function that increases or decreases the quantity of items in the cart.

To implement this, you'll need to find the queries and mutations in the Shopify GraphQL API documentation, specifically the ones related to cart operations.

Here are some potential functions you can add to your store:

  • Adding a function to increase or decrease the quantity of items in the cart
  • Adding a function to remove items from the cart
  • Login users and add a buyer identity to each cart

These functions will enhance the user experience and make your store more user-friendly.

Walter Brekke

Lead Writer

Walter Brekke is a seasoned writer with a passion for creating informative and engaging content. With a strong background in technology, Walter has established himself as a go-to expert in the field of cloud storage and collaboration. His articles have been widely read and respected, providing valuable insights and solutions to readers.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.