Skip to content
advanced Phase 115 · Headless

Headless Architecture in Magento 2

Headless commerce concepts, PWA, backend/frontend separation, and implementation strategies

1h
2 problems
Topic Progress 0%

Headless Commerce Concept

What is Headless Commerce?

Traditional vs Headless

Traditional:
┌─────────────────────────────┐
│         Magento             │
├─────────────────────────────┤
│  Backend + Frontend Tightly │
│  Coupled in Single App      │
└─────────────────────────────┘

Headless:
┌──────────────┐  ┌──────────────┐
│   Backend    │  │   Frontend   │
│   (Magento)  │  │   (PWA/Vue)  │
├──────────────┤  ├──────────────┤
│  API Layer   │──│  UI Layer    │
│  (GraphQL/   │  │  (Custom     │
│   REST)      │  │   Framework) │
└──────────────┘  └──────────────┘

Benefits of Headless

1. Frontend Freedom
   - Choose any frontend framework
   - Custom UI/UX without constraints
   - Faster frontend iterations

2. Omnichannel
   - Same backend for web, mobile, IoT
   - Consistent data across channels
   - API-first approach

3. Performance
   - Optimized frontend bundle
   - CDN-friendly static assets
   - Better Core Web Vitals

4. Scalability
   - Scale frontend and backend independently
   - Frontend: CDN + static hosting
   - Backend: API servers

When to Use Headless

Good candidates:
- High traffic requiring performance
- Multiple frontend channels (web, mobile, kiosk)
- Custom UX requirements
- Large development team
- Need for rapid frontend iterations

Not ideal for:
- Small catalogs (< 1000 products)
- Limited budget
- Small team
- Standard e-commerce UX sufficient
- Quick time to market

Magento Headless Options

1. Magento PWA Studio
   - Official Magento solution
   - Venia storefront reference
   - React-based

2. Vue Storefront
   - Community-driven
   - Vue.js based
   - Highly customizable

3. Custom Frontend
   - React/Next.js
   - Vue/Nuxt.js
   - Any framework

4. Hyva (Traditional but Decoupled)
   - Keeps Magento frontend
   - Modern Alpine.js + Tailwind
   - Not truly headless

API-First Design

Magento API Landscape

GraphQL API

# Product query
query getProduct($sku: String!) {
  products(filter: { sku: { eq: $sku } }) {
    items {
      name
      sku
      price_range {
        minimum_price {
          regular_price {
            value
            currency
          }
        }
      }
      description {
        html
      }
    }
  }
}

# Cart mutation
mutation createCart {
  createEmptyCart
}

mutation addToCart($cartId: String!, $qty: Int!, $sku: String!) {
  addSimpleProductsToCart(
    input: {
      cart_id: $cartId
      cart_items: [{ data: { quantity: $qty, sku: $sku } }]
    }
  ) {
    cart {
      items {
        product { name sku }
        quantity
      }
    }
  }
}

REST API

# Get products
GET /rest/V1/products?searchCriteria[pageSize]=10
Authorization: Bearer <token>

# Create order
POST /rest/V1/orders
Content-Type: application/json
Authorization: Bearer <token>

{
  "entity": {
    "payment_method": "checkmo",
    "items": [
      { "item_id": 1, "qty": 2 }
    ]
  }
}

Custom GraphQL Schema

# Custom module schema
type Query {
  customProducts(limit: Int): [CustomProduct]
  customProduct(sku: String!): CustomProduct
}

type CustomProduct {
  id: ID!
  name: String!
  sku: String!
  customField: String
}

# Custom resolver
class CustomProductResolver
{
    public function resolve(
        $value,
        array $args
    ): array {
        return $this->productService->getProducts($args['limit']);
    }
}

API Best Practices

1. Use GraphQL for complex queries
   - Reduces over-fetching
   - Single request for multiple resources
   - Strongly typed

2. REST for simple operations
   - Standard HTTP methods
   - Easy to cache
   - Wide tool support

3. Authentication
   - OAuth 2.0 for web apps
   - JWT for SPAs
   - API keys for server-to-server

4. Rate Limiting
   - Protect against abuse
   - Different limits per endpoint
   - Graceful degradation

PWA Architecture

PWA Components

Service Worker

// sw.js - Service Worker
const CACHE_NAME = 'magento-pwa-v1';
const urlsToCache = [
  '/',
  '/static/css/main.css',
  '/static/js/main.js'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(urlsToCache))
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

App Shell

<!-- Minimal HTML shell -->
<!DOCTYPE html>
<html>
<head>
  <title>My Store</title>
  <link rel="manifest" href="/manifest.json">
  <meta name="theme-color" content="#1976d2">
</head>
<body>
  <div id="app"></div>
  <script src="/static/js/app.js"></script>
</body>
</html>

Offline Support

// Cache strategies
const strategies = {
  // Cache first, network fallback
  cacheFirst: async (request) => {
    const cached = await caches.match(request);
    return cached || fetch(request);
  },
  
  // Network first, cache fallback
  networkFirst: async (request) => {
    try {
      const response = await fetch(request);
      const cache = await caches.open('data');
      cache.put(request, response.clone());
      return response;
    } catch {
      return caches.match(request);
    }
  },
  
  // Stale while revalidate
  staleWhileRevalidate: async (request) => {
    const cached = await caches.match(request);
    const fetchPromise = fetch(request).then(response => {
      const cache = await caches.open('data');
      cache.put(request, response.clone());
      return response;
    });
    return cached || fetchPromise;
  }
};

PWA Performance

Target Metrics:
- First Contentful Paint: < 1.5s
- Largest Contentful Paint: < 2.5s
- Time to Interactive: < 3.5s
- Cumulative Layout Shift: < 0.1

Optimization:
1. Code splitting
2. Lazy loading
3. Image optimization
4. CDN caching
5. Service worker caching

Implementation Strategy

Migration to Headless

Phase 1: API Enhancement

Duration: 4-8 weeks

Tasks:
- Audit existing API coverage
- Add missing GraphQL endpoints
- Implement custom resolvers
- Add rate limiting
- Improve API documentation

Deliverables:
- Complete GraphQL schema
- API documentation
- Performance benchmarks

Phase 2: Frontend Foundation

Duration: 8-12 weeks

Tasks:
- Set up PWA framework
- Implement app shell
- Create core components
- Integrate with Magento GraphQL
- Set up CI/CD

Deliverables:
- Working PWA skeleton
- Core page templates
- Deployment pipeline

Phase 3: Feature Parity

Duration: 12-16 weeks

Tasks:
- Implement all page types
- Build checkout flow
- Add search/filtering
- Implement user account
- Add admin features

Deliverables:
- Feature-complete frontend
- All user journeys working
- Performance optimized

Phase 4: Launch & Optimize

Duration: 4-8 weeks

Tasks:
- Beta testing
- Performance optimization
- SEO implementation
- Analytics integration
- Go-live

Deliverables:
- Production deployment
- Monitoring setup
- Documentation

Team Structure

Headless Team:
- 2-3 Frontend developers (React/Vue)
- 1-2 Backend developers (Magento API)
- 1 DevOps engineer
- 1 QA engineer
- 1 UX designer

Total: 6-8 people for 6-9 months

Cost Considerations

$headlessCosts = [
    'development' => [
        'frontend' => 200000,  // 6 months
        'backend' => 80000,    // 3 months
        'devops' => 40000,     // 2 months
        'total' => 320000
    ],
    'infrastructure' => [
        'frontend_cdn' => 100,  // monthly
        'api_servers' => 500,   // monthly
        'total_monthly' => 600
    ],
    'maintenance' => [
        'annual' => 60000
    ]
];

// Compare to traditional
$traditionalCosts = [
    'development' => 150000,
    'infrastructure' => 1200,
    'maintenance' => 40000
];

// Headless premium: ~2x initial, similar ongoing

Practice Problems

0 / 2 solved
Headless Architecture Design

Design a headless architecture for a Magento store requiring web, mobile, and kiosk frontends.

PWA Implementation

Implement a PWA storefront with offline support for product browsing.

Quiz

1. What is headless commerce?

Question 1 options

2. When is headless NOT recommended?

Question 2 options

3. What is the primary benefit of headless?

Question 3 options

4. What API does Magento PWA Studio use?

Question 4 options

Flashcards

Question

What is headless commerce?

Answer

Decoupled frontend and backend, communicating via APIs

Question

When to use headless?

Answer

High traffic, multiple channels, custom UX, large team

Question

What is PWA?

Answer

Progressive Web App: offline support, app-like experience, service workers

Question

What API for headless Magento?

Answer

GraphQL (primary) and REST (secondary)

Question

How long for headless migration?

Answer

6-9 months with 6-8 person team

Revision Notes

Key Takeaways

  • 1. Headless = decoupled frontend/backend, communicating via APIs
  • 2. Good for: high traffic, multiple channels, custom UX
  • 3. Not ideal for: small catalogs, limited budget, small teams
  • 4. Magento supports GraphQL (primary) and REST APIs
  • 5. PWA = offline support, app-like experience, service workers
  • 6. Migration takes 6-9 months with 6-8 person team

Interview Tips

  • Explain headless commerce and when to use it
  • Compare headless vs traditional Magento
  • Describe the PWA architecture and benefits
  • What are the challenges of headless implementation?
  • How do you plan a migration to headless?

Cheat Sheet

Headless Architecture Cheat Sheet

What: Decoupled frontend/backend via APIs

Benefits:

  • Frontend freedom
  • Omnichannel
  • Performance
  • Scalability

When to Use:

  • High traffic
  • Multiple channels
  • Custom UX
  • Large team

APIs:

  • GraphQL (primary)
  • REST (secondary)

PWA:

  • Service workers
  • Offline support
  • App shell
  • Caching strategies

Timeline: 6-9 months, 6-8 people