Contenuto articolo
- WordPress Headless con Next.js: Architettura Moderna per E-commerce Scalabili
- 🎯 Introduzione: Perché Headless WordPress?
- 🏗️ Architettura del Sistema
- 📋 Prerequisiti
- 🚀 Configurazione Backend WordPress
- 💻 Sviluppo Frontend Next.js
- 🛒 Componenti E-commerce
- 📊 Ottimizzazione SEO e Performance
- 🔒 Sicurezza
- 🚀 Deployment su Vercel
- 📈 Monitoraggio e Analytics
- 📊 Caso Studio: Sito da 10K Visite/Giorno
- 🎯 Conclusioni
- 📚 Risorse Utili
WordPress Headless con Next.js: Architettura Moderna per E-commerce Scalabili
Guida completa per costruire un e-commerce performante usando WordPress come backend headless e Next.js per il frontend. Dalla configurazione al deployment su Vercel.
🎯 Introduzione: Perché Headless WordPress?
Nel panorama e-commerce del 2026, le aspettative degli utenti sono più alte che mai:
- ⚡ Tempo di caricamento: < 2 secondi
- 📱 Mobile-first: Esperienza nativa su tutti i dispositivi
- 🔒 Sicurezza: Protezione da attacchi e data breach
- 📈 Scalabilità: Gestione di picchi di traffico senza downtime
L'architettura headless separa il backend (WordPress + WooCommerce) dal frontend (Next.js), offrendo:
| Vantaggio | WordPress Tradizionale | WordPress Headless |
|---|---|---|
| Performance | 3-5s load time | 0.5-1.5s load time |
| SEO | Buono | Eccellente (SSR/SSG) |
| Sicurezza | Vulnerabile plugin | API isolate |
| Scalabilità | Limitata | Illimitata (CDN) |
| Flessibilità | Temi predefiniti | Custom completo |
🏗️ Architettura del Sistema
┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (Next.js) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Pagine │ │ Componenti │ │ Gestione Stato │ │
│ │ (SSR/SSG) │ │ React │ │ (Zustand/Redux) │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
↓ HTTPS/API
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (WordPress + WooCommerce) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ REST API │ │ GraphQL │ │ Database │ │
│ │ /wp-json │ │ (WPGraphQL)│ │ MySQL │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ SERVIZI ESTERNI │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Stripe │ │ CDN │ │ Analytics │ │
│ │ Payments │ │ (Vercel) │ │ (Google/GA4) │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
📋 Prerequisiti
Requisiti Tecnici
- WordPress: 6.0+ (ultimo: 6.9.4)
- WooCommerce: 8.0+
- PHP: 8.1+
- Node.js: 18.0+ (LTS)
- Next.js: 14.0+
Plugin WordPress Necessari
- WooCommerce (gratuito) - E-commerce engine
- WPGraphQL (gratuito) - API GraphQL
- WPGraphQL for WooCommerce (gratuito) - Estensione WooCommerce
- Advanced Custom Fields (opzionale) - Campi custom
- JWT Authentication (gratuito) - Autenticazione API
# Installazione plugin via WP-CLI
wp plugin install woocommerce --activate
wp plugin install wpgraphql --activate
wp plugin install wp-graphql-woocommerce --activate
wp plugin install jwt-authentication-for-wp-rest-api --activate
🚀 Configurazione Backend WordPress
1. Configurazione WPGraphQL
Dopo aver installato i plugin, verifica che le API siano accessibili:
# Test endpoint GraphQL
wp eval 'echo graphql_endpoint();'
# Output: /graphql
2. Configurazione CORS
Aggiungi al file functions.php del tema child:
<?php
// Abilita CORS per il frontend Next.js
add_action('init', function() {
$allowed_origin = 'https://tuosito.vercel.app';
header("Access-Control-Allow-Origin: {$allowed_origin}");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Credentials: true");
});
3. Ottimizzazione API
// functions.php - Ottimizza risposte API
add_filter('graphql_query_amount_limit', function() {
return 100; // Limite query per sicurezza
});
// Cache delle risposte API
add_filter('graphql_cache_enabled', '__return_true');
💻 Sviluppo Frontend Next.js
1. Setup Progetto
# Crea nuovo progetto Next.js
npx create-next-app@latest wp-headless-ecommerce --typescript --tailwind --app
cd wp-headless-ecommerce
# Installa dipendenze
npm install @apollo/client graphql
npm install zustand axios
npm install stripe @stripe/stripe-js
2. Configurazione Apollo Client
Crea lib/apollo.ts:
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
const client = new ApolloClient({
ssrMode: typeof window === 'undefined',
link: new HttpLink({
uri: process.env.NEXT_PUBLIC_WP_GRAPHQL_URL, // https://mrtux.it/graphql
credentials: 'include',
}),
cache: new InMemoryCache({
typePolicies: {
Product: {
keyFields: ['databaseId'],
},
},
}),
});
export default client;
3. Environment Variables
Crea .env.local:
NEXT_PUBLIC_WP_GRAPHQL_URL=https://mrtux.it/graphql
NEXT_PUBLIC_WP_REST_URL=https://mrtux.it/wp-json
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
NEXT_PUBLIC_SITE_URL=https://tuosito.vercel.app
🛒 Componenti E-commerce
1. Fetch Prodotti da WooCommerce
components/ProductList.tsx:
import { gql, useQuery } from '@apollo/client';
const GET_PRODUCTS = gql`
query GetProducts($first: Int!) {
products(first: $first) {
nodes {
databaseId
name
slug
description
price
regularPrice
salePrice
images {
nodes {
sourceUrl
altText
}
}
categories {
nodes {
name
slug
}
}
}
}
}
`;
export default function ProductList({ limit = 12 }) {
const { data, loading, error } = useQuery(GET_PRODUCTS, {
variables: { first: limit },
});
if (loading) return <div>Caricamento...</div>;
if (error) return <div>Errore: {error.message}</div>;
return (
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{data.products.nodes.map((product: any) => (
<ProductCard key={product.databaseId} product={product} />
))}
</div>
);
}
2. Carrello con Zustand
store/cartStore.ts:
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
interface CartItem {
id: number;
name: string;
price: number;
quantity: number;
image: string;
}
interface CartState {
items: CartItem[];
addItem: (item: CartItem) => void;
removeItem: (id: number) => void;
updateQuantity: (id: number, quantity: number) => void;
clearCart: () => void;
total: () => number;
}
export const useCartStore = create<CartState>()(
persist(
(set, get) => ({
items: [],
addItem: (item) => {
const items = get().items;
const existing = items.find((i) => i.id === item.id);
if (existing) {
set({
items: items.map((i) =>
i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
),
});
} else {
set({ items: [...items, { ...item, quantity: 1 }] });
}
},
removeItem: (id) =>
set({ items: get().items.filter((i) => i.id !== id) }),
updateQuantity: (id, quantity) =>
set({
items: get().items.map((i) =>
i.id === id ? { ...i, quantity } : i
),
}),
clearCart: () => set({ items: [] }),
total: () =>
get().items.reduce((sum, item) => sum + item.price * item.quantity, 0),
}),
{ name: 'cart-storage' }
)
);
3. Checkout con Stripe
components/Checkout.tsx:
import { loadStripe } from '@stripe/stripe-js';
import { useCartStore } from '@/store/cartStore';
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);
export default function Checkout() {
const { items, total, clearCart } = useCartStore();
const handleCheckout = async () => {
const stripe = await stripePromise;
// Crea sessione checkout su backend
const response = await fetch('/api/create-checkout-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items }),
});
const session = await response.json();
// Redirect a Stripe
const result = await stripe!.redirectToCheckout({
sessionId: session.id,
});
if (result.error) {
alert(result.error.message);
}
};
return (
<button
onClick={handleCheckout}
className="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700"
>
Paga ora (€{total().toFixed(2)})
</button>
);
}
📊 Ottimizzazione SEO e Performance
1. Generazione Statica (SSG)
app/products/[slug]/page.tsx:
import { gql } from '@apollo/client';
import { apolloClient } from '@/lib/apollo';
export async function generateStaticParams() {
const { data } = await apolloClient.query({
query: gql`
query GetProductSlugs {
products(first: 100) {
nodes {
slug
}
}
}
`,
});
return data.products.nodes.map((product: any) => ({
slug: product.slug,
}));
}
export default async function ProductPage({ params }: { params: { slug: string } }) {
// Fetch dati prodotto...
return <div>...</div>;
}
2. Metadata Dinamici
export async function generateMetadata({ params }: { params: { slug: string } }) {
const product = await getProduct(params.slug);
return {
title: `${product.name} | MRTUX E-commerce`,
description: product.description,
openGraph: {
images: [product.image],
},
};
}
3. Image Optimization
import Image from 'next/image';
<Image
src={product.image}
alt={product.name}
width={400}
height={400}
priority
className="rounded-lg"
/>
🔒 Sicurezza
1. Rate Limiting API
middleware.ts:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Rate limiting semplice
const ip = request.ip ?? '127.0.0.1';
// Implementa logica rate limiting...
return NextResponse.next();
}
2. Validazione Input
// API Route - /api/create-checkout-session
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
// Valida input
if (!body.items || !Array.isArray(body.items)) {
return NextResponse.json(
{ error: 'Invalid cart data' },
{ status: 400 }
);
}
// Procedi con creazione sessione Stripe...
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
🚀 Deployment su Vercel
1. Connetti Repository GitHub
# Inizializza git
git init
git add .
git commit -m "Initial commit: WP Headless E-commerce"
# Push su GitHub
git remote add origin https://github.com/tuo-username/wp-headless-ecommerce.git
git push -u origin main
2. Configura Vercel
- Vai su vercel.com
- Importa il repository GitHub
- Configura le environment variables
- Deploy automatico ad ogni push
3. Custom Domain
# Aggiungi dominio su Vercel Dashboard
# mrtux-shop.vercel.app → shop.mrtux.it
📈 Monitoraggio e Analytics
1. Google Analytics 4
components/GoogleAnalytics.tsx:
import Script from 'next/script';
export default function GoogleAnalytics() {
return (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
/>
<Script
id="gtag-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}');
`,
}}
/>
</>
);
}
2. Vercel Analytics
import { Analytics } from '@vercel/analytics/react';
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
);
}
📊 Caso Studio: Sito da 10K Visite/Giorno
Performance Prima/Dopo
| Metrica | WordPress Tradizionale | Headless Next.js | Miglioramento |
|---|---|---|---|
| First Contentful Paint | 2.8s | 0.9s | -68% |
| Time to Interactive | 4.2s | 1.4s | -67% |
| PageSpeed Score | 72 | 96 | +33% |
| Bounce Rate | 48% | 31% | -35% |
| Conversion Rate | 2.1% | 2.8% | +33% |
Costi Mensili
| Servizio | Costo |
|---|---|
| Hosting WordPress | €20/mese |
| Vercel Pro | €20/mese |
| Stripe Fees | 1.4% + €0.25 |
| Totale | €40/mese + fees |
🎯 Conclusioni
L'architettura headless con WordPress + Next.js offre:
✅ Performance superiori - Caricamento < 1 secondo
✅ SEO eccellente - SSR/SSG per indicizzazione ottimale
✅ Sicurezza migliorata - API isolate, niente esposizione diretta del backend
✅ Scalabilità illimitata - CDN globale di Vercel
✅ Developer Experience - React moderno + WordPress familiare
Quando Scegliere Headless
- 📈 Traffico > 5K visite/giorno
- 🛒 E-commerce con checkout custom
- 🎨 Design altamente personalizzato
- 🌍 Audience globale (CDN essenziale)
Quando Evitare
- 📝 Blog semplice (< 1K visite/giorno)
- 💰 Budget limitato (< €50/mese)
- 👤 Team senza competenze React/Node
📚 Risorse Utili
- Documentazione Next.js
- WPGraphQL Documentation
- WooCommerce REST API
- Vercel Deployment Guide
- Stripe Integration
Hai trovato utile questa guida? Condividi i tuoi risultati nei commenti o contattaci per una consulenza personalizzata sulla tua architettura e-commerce!
Pubblicato su mrtux.it - 4 Aprile 2026
Categoria: Sviluppo WordPress, E-commerce, Next.js




Lascia un commento