magento10 phút đọc
Magento Headless Commerce với Next.js: Kiến trúc và Triển khai
Xây dựng storefront Magento headless dùng Next.js và GraphQL — tích hợp, quản lý giỏ hàng, xác thực và kết quả hiệu năng.
V
Bởi Ventra Rocket#Magento#Headless Commerce#Next.js#GraphQL#PWA
Kiến trúc headless tách frontend Next.js khỏi backend Magento qua GraphQL, cho storefront nhanh hơn trong khi vẫn giữ được toàn bộ chức năng thương mại.
Kiến trúc
Trình duyệt khách hàng
Next.js Frontend (ISR cho catalog, client-side cho giỏ hàng)
Magento GraphQL API (sản phẩm, giỏ hàng, auth, đơn hàng)
Magento Backend (database, thanh toán, tồn kho)
1. GraphQL Client
import { GraphQLClient } from "graphql-request";
export function getMagentoClient(token?: string) {
return new GraphQLClient(process.env.MAGENTO_GRAPHQL_URL!, {
headers: {
"Content-Type": "application/json",
...(token && { Authorization: `Bearer ${token}` }),
},
});
}
2. Product Listing với ISR
const GET_PRODUCTS = `
query GetProducts($urlKey: String!, $pageSize: Int!) {
categoryList(filters: { url_key: { eq: $urlKey } }) {
products(pageSize: $pageSize) {
total_count
items { uid sku name url_key }
}
}
}
`;
export const revalidate = 900; // ISR: 15 phút
3. Quản lý Giỏ hàng
const ADD_TO_CART = `
mutation AddToCart($cartId: String!, $sku: String!, $quantity: Float!) {
addSimpleProductsToCart(input: {
cart_id: $cartId
cart_items: [{ data: { sku: $sku, quantity: $quantity } }]
}) {
cart { prices { grand_total { value currency } } }
}
}
`;
4. Kết quả Hiệu năng
| Metric | Trước (Luma) | Sau (Headless) | |--------|-------------|----------------| | LCP | 5.8s | 1.2s | | PageSpeed | 42 | 91 | | Tỷ lệ thoát | 68% | 44% |
Kết luận
Magento Headless + Next.js: ISR cho catalog, client-side giỏ hàng, server actions cho auth. Ventra Rocket đã deploy nhiều dự án với PageSpeed 90+.