How to Use Shopify’s Storefront API for Headless Commerce
by Aayushi Patel, Shopify Team Lead
Headless commerce is becoming increasingly popular as it allows for greater flexibility, customization, and performance. Shopify’s Storefront API is a powerful tool that enables developers to create custom shopping experiences by decoupling the frontend from the backend. In this blog post, we’ll explore how to use Shopify’s Storefront API to build a headless e-commerce store.
1. Setting Up Your Shopify Storefront API
First, you need to enable the Storefront API for your Shopify store. Follow these steps:
- Log in to your Shopify Admin panel.
- Navigate to Apps and click on Manage private apps..
- Click Create a new private app.
- Provide a name for your app and set the necessary permissions.
- Under Storefront API, ensure you enable all the permissions required.
You will receive an API key and access token. Keep these credentials safe as you will need them to authenticate your API requests.
2. Setting Up Your Development Environment
For this tutorial, we will use Node.js and Express to create a simple server. Ensure you have Node.js installed on your machine. If not, you can download it from here.
Initialize a new Node.js project:
mkdir headless-shopify cd headless-shopify npm init -y
Install the necessary dependencies:
npm install express axios
3. Creating Your Express Server
Create a new file named server.js and add the following code to set up a basic Express server:
const express = require('express'); const axios = require('axios'); const app = express(); const PORT = 3000; app.use(express.json()); const SHOPIFY_API_URL = 'https://your-store.myshopify.com/api/2023-01/graphql.json'; const STOREFRONT_ACCESS_TOKEN = 'your-storefront-access-token'; // GraphQL query to fetch products const PRODUCTS_QUERY = ` { products(first: 10) { edges { node { id title description images(first: 1) { edges { node { src } } } variants(first: 1) { edges { node { price } } } } } } } `; app.get('/products', async (req, res) => { try { const response = await axios.post( SHOPIFY_API_URL, { query: PRODUCTS_QUERY }, { headers: { 'Content-Type': 'application/json', 'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN, }, } ); res.status(200).json(response.data.data.products.edges); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
4. Fetching and Displaying Products
With your server set up, you can now fetch products from your Shopify store using the Storefront API. The above GraphQL query retrieves the first 10 products, including their ID, title, description, image, and price.
Start your server by running:
node server.js
You can access the list of products by navigating to http://localhost:3000/products in your browser. This endpoint will return a JSON response containing the product details.
5. Building the Frontend
Now that we have a backend server to fetch products, let’s create a simple frontend to display them. For this, we will use React.
Set up a new React app:
npx create-react-app headless-shopify-frontend cd headless-shopify-frontend
Install Axios for making HTTP requests:
npm install axios
Create a new component named Products.js:
import React, { useEffect, useState } from 'react'; import axios from 'axios'; const Products = () => { const [products, setProducts] = useState([]); useEffect(() => { const fetchProducts = async () => { try { const response = await axios.get('http://localhost:3000/products'); setProducts(response.data); } catch (error) { console.error('Error fetching products:', error); } }; fetchProducts(); }, []); return ( <div> <h1>Products</h1> <ul> {products.map((product) => ( <li key={product.node.id}> <h2>{product.node.title}</h2> <p>{product.node.description}</p> <img src={product.node.images.edges[0].node.src} alt={product.node.title} /> <p>Price: ${product.node.variants.edges[0].node.price}</p> </li> ))} </ul> </div> ); }; export default Products;
Integrate the Products component into your main App.js:
import React from 'react'; import Products from './Products'; function App() { return ( <div className="App"> <Products /> </div> ); } export default App;
Run your React app:
npm start
Your React app will start on http://localhost:3000, and it should display a list of products fetched from your Shopify store.
Conclusion
By leveraging Shopify’s Storefront API, you can create highly customized, headless e-commerce solutions that provide a unique shopping experience. This tutorial demonstrated how to set up a Node.js server to fetch products from Shopify and display them in a React frontend. With these foundations, you can further customize your headless store to meet your specific needs.