Magento 2 GraphQL in Frontend

🔍 Magento 2 GraphQL in Frontend – Fetch Data with Modern Queries

Magento 2 supports GraphQL as a powerful alternative to REST APIs. It’s perfect for frontend developers who need precise control over what data is fetched from the backend. Whether you’re using PWA Studio or custom JavaScript, GraphQL lets you get exactly what you want—no more, no less!

📬 What is GraphQL?

GraphQL is a query language that allows clients to define the structure of the response. Instead of multiple endpoints like REST, GraphQL uses a single endpoint with flexible queries.

🛠️ Basic GraphQL Endpoint

The Magento 2 GraphQL endpoint is:

https://your-magento-site.com/graphql

📦 Example: Fetch Product Name and Price

query {
  products(filter: { sku: { eq: "24-MB01" } }) {
    items {
      name
      sku
      price {
        regularPrice {
          amount {
            value
            currency
          }
        }
      }
    }
  }
}

Try It Now

🧪 Run GraphQL in Browser (Altair, Postman, etc.)

Install Altair GraphQL Client browser extension or use GraphQL Playground. Paste the query above, set your Magento endpoint, and hit “Run”.

🧩 Use GraphQL in Frontend JavaScript

async function fetchProduct() {
  const query = `
    query {
      products(filter: { sku: { eq: "24-MB01" } }) {
        items {
          name
          sku
          price {
            regularPrice {
              amount {
                value
                currency
              }
            }
          }
        }
      }
    }
  `;

  const response = await fetch("https://your-magento-site.com/graphql", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ query })
  });

  const data = await response.json();
  console.log(data.data.products.items);
}

Try It Now

⚙️ In PWA Studio (Apollo Client)

If you’re using Magento PWA Studio, GraphQL queries are integrated using Apollo Client, which handles caching, hooks, and errors efficiently.

import { useQuery, gql } from '@apollo/client';

const GET_PRODUCTS = gql`
  query {
    products(filter: { sku: { eq: "24-MB01" } }) {
      items {
        name
        sku
      }
    }
  }
`;

export default function ProductBlock() {
  const { loading, error, data } = useQuery(GET_PRODUCTS);

  if (loading) return 

Loading...

; if (error) return

Error!

; return

{data.products.items[0].name}

; }

Try It Now

📌 Summary

  • GraphQL gives you full control over the frontend data you retrieve from Magento 2.
  • Use it via tools like Altair or in frontend JS using fetch() or Apollo Client.
  • Perfect for building modern storefronts with PWA Studio or React apps.

Magento’s GraphQL is developer-friendly, powerful, and future-proof. Give it a try and make your frontend faster and smarter!