Skip to content

Nairobi · East Africa

E-commerce & Shopify

How to Build a Shopify Storefront Using Angular

Build a headless Shopify storefront in Angular with the Storefront GraphQL API: a typed service, product listing, cartCreate, checkout redirect and SSR tips.

TechBytes EA Engineering Team· · 12 min read

Shopper browsing an online store on a laptop with a card in hand

Shopify's themes are fine for most stores, but some teams need a storefront that lives inside an existing Angular application, shares a design system with a customer portal, or performs better on low-end Android phones over mobile data. The Shopify Storefront API makes that possible: Shopify keeps running products, inventory, checkout and payments, while you own the frontend. This guide walks through a working Angular implementation using standalone components, a typed GraphQL service, product listing, cart creation with cartCreate and the redirect to Shopify checkout, plus the server-side rendering decisions that matter for SEO and speed.

Key takeaways

  • The Storefront API is a public GraphQL API. You POST queries to https://<store>.myshopify.com/api/<version>/graphql.json with the X-Shopify-Storefront-Access-Token header.
  • The public Storefront access token is designed to be used in browsers. Never ship an Admin API token or a private Storefront token to the client.
  • Use cartCreate to build a cart and redirect the customer to the cart's checkoutUrl. Shopify's hosted checkout handles payment, including the M-Pesa and card gateways you have configured.
  • With Angular SSR, render product listings on the server for SEO and fast first paint, but create carts and touch localStorage only in the browser.
  • Pin an API version and plan to upgrade it. Shopify releases versions quarterly and retires old ones.

Architecture

Browser (Angular app, hydrated)
   |  product pages rendered on server, then hydrated
   |
   |  POST GraphQL (public Storefront token)
   v
Shopify Storefront API  ---- products, collections, prices, inventory
   |
   |  cartCreate / cartLinesAdd -> returns cart.id + cart.checkoutUrl
   v
Shopify hosted checkout (shop domain or checkout subdomain)
   |
   v
Payment gateways configured in Shopify admin
(e.g. Pesapal, Flutterwave, Paystack, M-Pesa apps where available)

The key design choice is that checkout stays on Shopify. You do not handle card data or M-Pesa callbacks in Angular, which keeps your PCI scope and payment integration work minimal.

Prerequisites

  1. A Shopify store on a plan that supports headless storefronts.
  2. A Storefront API access token. Install Shopify's Headless channel or create a custom app in the admin with Storefront API access, and grant the scopes for reading products and managing carts. Copy the public access token.
  3. An Angular project on a recent version with standalone components and the built-in control flow (@if, @for), which arrived in Angular 17. Create one with ng new storefront --ssr to include server-side rendering.
  4. An API version. Check the currently supported versions on shopify.dev. The examples below use 2026-10; substitute a version that is currently supported when you build.

Shopify's Storefront API reference lives at shopify.dev, and Angular's documentation for HttpClient, signals and SSR is at angular.dev.

Overhead view of a developer workstation with code on two monitorsA typical engineering setup: editor, terminal and the running app side by side.

Step 1: Configure HttpClient and the Shopify settings

Register HttpClient with the fetch backend, which works well with SSR, and provide the Shopify configuration through an injection token.

// src/app/shopify/shopify.config.ts
import { InjectionToken } from '@angular/core';

export interface ShopifyConfig {
  storeDomain: string;      // e.g. 'your-store.myshopify.com'
  storefrontToken: string;  // public Storefront API token
  apiVersion: string;       // e.g. '2026-10'
  country: string;          // ISO country code for contextual pricing, e.g. 'KE'
}

export const SHOPIFY_CONFIG = new InjectionToken<ShopifyConfig>('SHOPIFY_CONFIG');
// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import {
  provideClientHydration,
  withHttpTransferCacheOptions,
} from '@angular/platform-browser';
import { routes } from './app.routes';
import { SHOPIFY_CONFIG } from './shopify/shopify.config';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(withFetch()),
    // GraphQL uses POST; opt in so server-fetched product data is reused on hydration.
    provideClientHydration(withHttpTransferCacheOptions({ includePostRequests: true })),
    {
      provide: SHOPIFY_CONFIG,
      useValue: {
        storeDomain: 'your-store.myshopify.com',
        storefrontToken: 'your-public-storefront-token',
        apiVersion: '2026-10',
        country: 'KE',
      },
    },
  ],
};

In a real project, load these values from environment files or a build-time configuration rather than hard-coding them. The public token is not secret in the way an Admin token is, but keeping configuration out of source makes rotation easier.

Step 2: A typed GraphQL service

This service wraps every Storefront API call: it builds the endpoint, sets the required headers and surfaces GraphQL errors, which arrive with an HTTP 200 status and an errors array.

// src/app/shopify/storefront.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import { SHOPIFY_CONFIG } from './shopify.config';

interface GraphQLResponse<T> {
  data?: T;
  errors?: { message: string }[];
}

@Injectable({ providedIn: 'root' })
export class StorefrontService {
  private readonly http = inject(HttpClient);
  private readonly config = inject(SHOPIFY_CONFIG);
  private readonly endpoint =
    `https://${this.config.storeDomain}/api/${this.config.apiVersion}/graphql.json`;
  private readonly headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'X-Shopify-Storefront-Access-Token': this.config.storefrontToken,
  });

  get country(): string {
    return this.config.country;
  }

  query<T>(query: string, variables: Record<string, unknown> = {}): Observable<T> {
    return this.http
      .post<GraphQLResponse<T>>(this.endpoint, { query, variables }, { headers: this.headers })
      .pipe(
        map((res) => {
          if (res.errors?.length) {
            throw new Error(res.errors.map((e) => e.message).join('; '));
          }
          if (!res.data) {
            throw new Error('Storefront API returned no data');
          }
          return res.data;
        }),
      );
  }
}

If you prefer the native fetch API, the request is the same: POST to the endpoint with a JSON body of { query, variables } and the same two headers. Using HttpClient gives you interceptors, testing utilities and SSR transfer caching.

Step 3: Fetch products

The query below fetches products with their first variant, a resized image and the minimum price. The @inContext directive asks Shopify for prices in the context of a country, which returns KES prices if your store has a Kenyan market configured in Shopify Markets; otherwise you receive your store's default currency.

// src/app/shopify/catalog.service.ts
import { Injectable, inject } from '@angular/core';
import { Observable, map } from 'rxjs';
import { StorefrontService } from './storefront.service';

export interface Money {
  amount: string;       // decimal as string, e.g. '2500.0'
  currencyCode: string; // e.g. 'KES'
}

export interface Product {
  id: string;
  title: string;
  handle: string;
  featuredImage: { url: string; altText: string | null } | null;
  priceRange: { minVariantPrice: Money };
  variants: { nodes: { id: string; availableForSale: boolean }[] };
}

const PRODUCTS_QUERY = `#graphql
  query Products($first: Int!, $country: CountryCode) @inContext(country: $country) {
    products(first: $first, sortKey: BEST_SELLING) {
      nodes {
        id
        title
        handle
        featuredImage {
          url(transform: { maxWidth: 600 })
          altText
        }
        priceRange {
          minVariantPrice { amount currencyCode }
        }
        variants(first: 1) {
          nodes { id availableForSale }
        }
      }
    }
  }
`;

@Injectable({ providedIn: 'root' })
export class CatalogService {
  private readonly storefront = inject(StorefrontService);

  listProducts(first = 12): Observable<Product[]> {
    return this.storefront
      .query<{ products: { nodes: Product[] } }>(PRODUCTS_QUERY, {
        first,
        country: this.storefront.country,
      })
      .pipe(map((data) => data.products.nodes));
  }
}

Requesting a resized image with url(transform: { maxWidth: 600 }) matters on mobile data. Serving a full-resolution product photo to a phone on a congested LTE cell is one of the most common causes of slow headless storefronts.

Step 4: Create a cart and redirect to checkout

cartCreate takes a CartInput with line items (each a variant ID as merchandiseId plus a quantity) and returns the cart, including its checkoutUrl. Always check userErrors, which report problems such as an unavailable variant without failing the HTTP request.

// src/app/shopify/cart.service.ts
import { Injectable, PLATFORM_ID, inject, signal } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { Observable, map, tap } from 'rxjs';
import { StorefrontService } from './storefront.service';
import { Money } from './catalog.service';

export interface CartLineInput {
  merchandiseId: string;
  quantity: number;
}

export interface Cart {
  id: string;
  checkoutUrl: string;
  totalQuantity: number;
  cost: { totalAmount: Money };
}

interface CartCreateResult {
  cartCreate: {
    cart: Cart | null;
    userErrors: { field: string[] | null; message: string }[];
  };
}

const CART_CREATE = `#graphql
  mutation CartCreate($input: CartInput!, $country: CountryCode) @inContext(country: $country) {
    cartCreate(input: $input) {
      cart {
        id
        checkoutUrl
        totalQuantity
        cost { totalAmount { amount currencyCode } }
      }
      userErrors { field message }
    }
  }
`;

const CART_ID_KEY = 'shopify_cart_id';

@Injectable({ providedIn: 'root' })
export class CartService {
  private readonly storefront = inject(StorefrontService);
  private readonly platformId = inject(PLATFORM_ID);
  private readonly document = inject(DOCUMENT);

  readonly cart = signal<Cart | null>(null);

  createCart(lines: CartLineInput[]): Observable<Cart> {
    const country = this.storefront.country;
    return this.storefront
      .query<CartCreateResult>(CART_CREATE, {
        input: { lines, buyerIdentity: { countryCode: country } },
        country,
      })
      .pipe(
        map(({ cartCreate }) => {
          if (cartCreate.userErrors.length) {
            throw new Error(cartCreate.userErrors.map((e) => e.message).join('; '));
          }
          if (!cartCreate.cart) {
            throw new Error('Cart was not created');
          }
          return cartCreate.cart;
        }),
        tap((cart) => {
          this.cart.set(cart);
          this.saveCartId(cart.id);
        }),
      );
  }

  redirectToCheckout(cart: Cart): void {
    if (isPlatformBrowser(this.platformId)) {
      this.document.location.href = cart.checkoutUrl;
    }
  }

  private saveCartId(id: string): void {
    if (!isPlatformBrowser(this.platformId)) return;
    try {
      localStorage.setItem(CART_ID_KEY, id);
    } catch {
      // Storage can be unavailable (private mode, blocked storage); the cart still works this session.
    }
  }
}

For a full cart experience, add the cartLinesAdd, cartLinesUpdate and cartLinesRemove mutations, and reload an existing cart with the cart(id:) query using the stored ID. The pattern is identical: send the mutation, check userErrors, update the signal.

Step 5: The product list component

This standalone component renders the product grid with the built-in control flow and signals, and starts checkout with a single click.

// src/app/products/product-list.component.ts
import { Component, inject, signal } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, of } from 'rxjs';
import { CatalogService, Product } from '../shopify/catalog.service';
import { CartService } from '../shopify/cart.service';

@Component({
  selector: 'app-product-list',
  standalone: true,
  imports: [CurrencyPipe],
  template: `
    @if (error(); as message) {
      <p class="error" role="alert">{{ message }}</p>
    }

    <ul class="product-grid">
      @for (product of products(); track product.id) {
        <li class="product-card">
          @if (product.featuredImage; as image) {
            <img [src]="image.url" [alt]="image.altText ?? product.title" loading="lazy" />
          }
          <h2>{{ product.title }}</h2>
          <p>
            {{ product.priceRange.minVariantPrice.amount
               | currency: product.priceRange.minVariantPrice.currencyCode }}
          </p>
          @if (product.variants.nodes[0]; as variant) {
            <button
              type="button"
              [disabled]="!variant.availableForSale || pendingVariantId() !== null"
              (click)="buyNow(variant.id)">
              {{ variant.availableForSale ? 'Buy now' : 'Sold out' }}
            </button>
          }
        </li>
      } @empty {
        <li>No products available.</li>
      }
    </ul>
  `,
})
export class ProductListComponent {
  private readonly catalog = inject(CatalogService);
  private readonly cartService = inject(CartService);

  readonly error = signal<string | null>(null);
  readonly pendingVariantId = signal<string | null>(null);

  readonly products = toSignal(
    this.catalog.listProducts(12).pipe(
      catchError((err: Error) => {
        this.error.set('Products could not be loaded. Please try again.');
        console.error(err);
        return of([] as Product[]);
      }),
    ),
    { initialValue: [] as Product[] },
  );

  buyNow(variantId: string): void {
    this.error.set(null);
    this.pendingVariantId.set(variantId);
    this.cartService.createCart([{ merchandiseId: variantId, quantity: 1 }]).subscribe({
      next: (cart) => this.cartService.redirectToCheckout(cart),
      error: (err: Error) => {
        this.error.set(err.message);
        this.pendingVariantId.set(null);
      },
    });
  }
}

In Angular 19 and later, components are standalone by default, so standalone: true is optional; leaving it in keeps the code valid on Angular 17 and 18 as well. Wire the component into app.routes.ts with a route such as { path: '', component: ProductListComponent }.

About the checkout redirect

checkoutUrl points to Shopify's hosted checkout. When the customer lands there, Shopify presents the payment methods configured in your admin. For Kenyan stores, that typically means a third-party gateway such as Pesapal, Flutterwave or Paystack, or an M-Pesa app, because Shopify Payments is not available to Kenyan merchants at the time of writing. Our Shopify vs WooCommerce comparison covers these options.

Do not try to embed checkout in an iframe or proxy it; send the customer to the URL. After payment, Shopify shows its order status page. If you want customers back in your Angular app, configure links or use order webhooks to update your own systems.

Stacks of parcels ready for courier dispatchFulfilment speed is often the real bottleneck for growing online stores.

SSR considerations

Server-side rendering is where headless Angular storefronts win or lose on SEO and perceived speed.

  • Render catalogue pages on the server. Product listings and product detail pages should be in the initial HTML so search engines index them and users on slow connections see content before JavaScript finishes loading.
  • Enable POST transfer caching. Angular's HTTP transfer cache reuses GET and HEAD responses by default. GraphQL uses POST, so withHttpTransferCacheOptions({ includePostRequests: true }) prevents the browser from re-requesting the same product data during hydration.
  • Keep browser-only APIs behind platform checks. localStorage, window and redirects must only run in the browser, as in the CartService above. Cart creation should only ever happen in response to a user action.
  • Cache rendered pages carefully. Product pages can be cached at a CDN for short periods, but prices and stock change. Use short cache lifetimes or revalidation, and never cache cart or account responses.
  • Consider a server-side token for SSR. Shopify also offers private Storefront tokens for server-side requests, sent with the Shopify-Storefront-Private-Token header. Shopify recommends passing the buyer's IP in the Shopify-Storefront-Buyer-IP header on server-side requests so bot protection works correctly. Keep private tokens in server environment variables only.
  • Host near your customers. For Kenyan shoppers, deploy the SSR server in a region with good latency to East Africa and put a CDN in front of it. See our AWS, Azure and Google Cloud comparison for region trade-offs.

Performance on East African mobile networks

  • Request only the fields you render. GraphQL makes it easy to over-fetch.
  • Use image transforms and loading="lazy", and set image dimensions in CSS to avoid layout shift.
  • Keep the initial JavaScript bundle small; lazy-load routes for account, search and cart pages.
  • Test on a mid-range Android device over a throttled 3G or 4G profile. That is closer to reality for many shoppers than a developer laptop on office fibre.

Common mistakes

  • Using the Admin API from the browser. Admin tokens grant full store access. Only the public Storefront token belongs in client code.
  • Ignoring userErrors. Cart mutations can fail logically while returning HTTP 200. Always check them.
  • Calling localStorage during SSR. It does not exist on the server and will crash rendering. Guard with isPlatformBrowser.
  • Not pinning an API version. Shopify retires versions on a schedule. Pin one and schedule upgrades.
  • Rebuilding checkout. Shopify's checkout handles payments, taxes and fraud checks. Redirect to checkoutUrl instead of reinventing it.
  • Forgetting data protection. If you collect customer details in Angular before checkout, such as for a newsletter, the Kenya Data Protection Act 2019 applies. Collect only what you need and explain why.

FAQ

Is it safe to expose the Storefront API token in Angular?

The public Storefront access token is designed for client-side use and only grants the unauthenticated scopes you enable. Never expose Admin API tokens or private Storefront tokens in browser code.

Can I accept M-Pesa in a headless Angular Shopify store?

Yes, through Shopify's hosted checkout. Any M-Pesa-capable gateway configured in your Shopify admin appears at checkout after the redirect to checkoutUrl.

Do I need SSR for a Shopify Angular storefront?

Not strictly, but it is strongly recommended for public catalogue pages. SSR improves search indexing, social link previews and first paint on slow connections.

Should I use Shopify Hydrogen instead of Angular?

Hydrogen is Shopify's React-based framework and is a strong choice for new teams. Angular makes sense when your organisation already standardises on Angular or needs the storefront inside an existing Angular application.

Which Storefront API version should I use?

Use the latest stable version listed on shopify.dev when you start, pin it in configuration and plan an upgrade at least once a year.

How TechBytes can help

We build headless storefronts in Angular, React and Vue on top of Shopify, including SSR hosting, performance tuning for East African mobile networks and payment gateway configuration. We can also review an existing headless build for security, caching and checkout reliability. Contact our software development team, or see the best e-commerce technologies for growing businesses for the wider stack.

WhatsApp