blog.dopana

Quay lại

Khi nói về SPA (Single-Page Application) so với WordPress truyền thống, sự khác biệt chính nằm ở kiến trúc: SPA là một ứng dụng frontend hiện đại, trong khi WordPress là một CMS truyền thống. Nhưng chúng không nhất thiết phải đối đầu với nhau - có thể kết hợp cả hai.

SPA Web App vs WordPress Truyền thống#

Điểm khác biệt cơ bản#

SPA (Single-Page Application) và WordPress phục vụ các mục đích khác nhau và có kiến trúc khác nhau.

Headless WordPressWordPress Truyền thốngSPA Web AppFrontend: React/Vue/AngularBackend: Custom APIInteractive: HighFrontend: Theme + PHPBackend: WordPress/PHPInteractive: Low-MediumBackend: WordPress CMSAPI: REST/GraphQLFrontend: SPA Framework

Bảng so sánh chi tiết#

Tiêu chíSPA Web AppWordPress Truyền thống
Mục đích chínhỨng dụng tương tácQuản lý nội dung/site
FrontendJavaScript app (React/Vue)Theme + WordPress rendering
BackendCustom API/backendWordPress/PHP + database
Content editingCần xây dựng admin toolingCMS/editor có sẵn
User experienceRất động, giống appTốt cho pages, blogs, nội dung
SEOCần SSR/SSG/metadata setupThường khá đơn giản
PerformanceCó thể cực nhanh khi engineering tốtPhụ thuộc theme/plugins/hosting
Complex interactionsXuất sắcCó thể, nhưng cần custom dev
MaintenanceBạn sở hữu stack ứng dụngWordPress + theme/plugin updates
Plugins/ecosystemnpm/open-source librariesHệ sinh thái plugin WordPress lớn
Non-technical editingThường yếu nếu không build CMSĐiểm mạnh chính
Chi phí xây dựngThường cao cho app phức tạpThường nhanh/cheap cho site tiêu chuẩn

Khi nào nên chọn WordPress Truyền thống?#

WordPress là lựa chọn tốt nhất khi bạn chủ yếu cần:

  • Website công ty: Corporate website với pages tĩnh
  • Blog/tin tức: Content-heavy sites với blog posts
  • Landing pages: Marketing pages và promotions
  • Portfolio: Showcase galleries và projects
  • Documentation: Sites tài liệu và hướng dẫn
  • Marketing site: Promotional content sites
  • Nhiều editor quản lý nội dung: Non-technical users cần update content

[!NOTE] WordPress cơ bản là một CMS với khả năng publishing, editing và extension mở rộng. Nó được thiết kế để làm content management tốt nhất.

Khi nào nên chọn SPA?#

SPA là lựa chọn tốt nhất khi bạn chủ yếu cần:

  • Dashboard: Admin panels và analytics dashboards
  • SaaS product: Software-as-a-Service applications
  • Booking/application workflow: Quy trình đặt lịch và applications
  • Complex forms: Forms phức tạp với validation đa tầng
  • Real-time interaction: Real-time updates và live data
  • Highly interactive user accounts: User profiles với complex interactions
  • App-like navigation/state: Navigation phức tạp với state management
  • Complex client-side business logic: Logic nghiệp vụ phía client phức tạp

Headless WordPress: Khi nào nên kết hợp cả hai?#

Headless WordPress cho phép bạn dùng WordPress làm CMS/backend và xây dựng frontend như SPA. WordPress cung cấp REST API chính thức để xây dựng single-page applications.

Kiến trúc Headless WordPress#

Content EditorsWordPress CMSDatabaseREST API / GraphQLSPA FrontendReact / Vue / Next.jsUsers

Khi nào nên chọn SPA + WordPress?#

Chọn headless WordPress khi bạn cần cả application frontend phức tạp và content management dễ dàng.

Ví dụ thực tế: Booking platform

WordPress CMS:

  • Services pages
  • Blog articles
  • FAQs và documentation
  • Locations info
  • Marketing content

↓ REST API/GraphQL

React/Vue SPA:

  • Login/authentication
  • Search functionality
  • Booking flow phức tạp
  • Customer dashboard
  • Payment processing

Lợi ích của Headless WordPress#

  1. Performance: Frontend riêng biệt có thể đạt hiệu suất tối đa với SSR/SSG
  2. Flexibility: Full control over frontend experience với modern frameworks
  3. Scalability: Frontend và backend có thể scale độc lập
  4. Developer Experience: Modern tooling cho developers (React, Vue, Next.js)
  5. Content Management: Non-technical users vẫn dùng WordPress admin quen thuộc
  6. Security: Giảm attack surface bằng cách tách frontend khỏi backend
  7. Multi-channel: Một CMS có thể phục vụ nhiều frontend (web, mobile, apps)

Implement Headless WordPress#

Bước 1: Setup WordPress Backend#

# 1. Install WordPress sạch
# 2. Enable permalinks
# 3. Install plugins cần thiết
# - WP REST API (built-in since 4.7)
# - WPGraphQL (optional, cho GraphQL)
# - ACF (Advanced Custom Fields)
# - JWT Authentication (cho gated content)
bash

Bước 2: Configure REST API#

// functions.php - Setup CORS headers
add_action('rest_api_init', function () {
    remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
    add_filter('rest_pre_serve_request', function ($value) {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Credentials: true');
        return $value;
    });
}, 15);
php

Bước 3: Tạo Custom Post Types#

// functions.php - Register custom post type
function register_services_post_type() {
    register_post_type('services', [
        'label' => 'Services',
        'public' => true,
        'show_in_rest' => true, // Important for REST API
        'supports' => ['title', 'editor', 'thumbnail'],
    ]);
}
add_action('init', 'register_services_post_type');
php

Bước 4: SPA Frontend với React#

Bước 5: Sử dụng WPGraphQL (Optional)#

Các mô hình Hybrid phổ biến#

1. Hybrid: Embed SPA trong WordPress#

Giữ WordPress làm site chính, mount SPA vào page/template cụ thể.

Khi nên dùng:

  • Muốn giữ WordPress features/plugins
  • Cần SPA interactivity trên pages cụ thể (/app, /dashboard)
  • Muốn minimal infrastructure change

Ưu điểm:

  • Thay đổi infrastructure tối thiểu
  • Giữ WordPress admin/editor
  • Đường đến value nhanh nhất

Nhược điểm:

  • Vẫn ship client bundle
  • Deep SPA routes không phải WP pages chính thức

2. Full Headless: WordPress Backend + SPA Frontend#

Chạy WordPress nghiêm ngặt làm content platform, frontend là project riêng biệt.

Khi nên dùng:

  • Cần full control performance, SSR/SSG/ISR
  • Muốn modern DX và routing
  • Cần edge rendering và optimizations

Ưu điểm:

  • Full control over frontend
  • Performance tối đa với modern frameworks
  • Developer experience tốt hơn

Nhược điểm:

  • Setup phức tạp hơn
  • Cần maintain hai codebases

Best Practices cho Headless WordPress#

1. Performance Optimization#

// Implement caching cho API calls
import { useSWR } from 'swr';

function useWordPressData(endpoint) {
    const { data, error } = useSWR(endpoint, fetcher, {
        revalidateOnFocus: false,
        revalidateOnReconnect: false,
        dedupingInterval: 60000, // 1 minute
    });
    
    return { data, error };
}
javascript

2. SEO với Next.js SSR#

// Next.js pages với SSR cho SEO
export async function getServerSideProps(context) {
    const res = await fetch('https://your-site.com/wp-json/wp/v2/posts');
    const posts = await res.json();
    
    return {
        props: {
            posts,
        },
    };
}
javascript

3. Authentication#

// JWT authentication flow
async function login(credentials) {
    const response = await fetch('https://your-site.com/wp-json/jwt-auth/v1/token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials),
    });
    
    const { token } = await response.json();
    localStorage.setItem('jwt_token', token);
}
javascript

4. Image Optimization#

// Optimize images từ WordPress
import Image from 'next/image';

function OptimizedImage({ imageUrl, alt }) {
    return (
        <Image
            src={imageUrl}
            alt={alt}
            width={800}
            height={600}
            loading="lazy"
        />
    );
}
javascript

Tương lai của Web Development#

Theo nghiên cứu năm 2025, 64% enterprise businesses sử dụng WordPress đã implement hoặc đang khám phá headless configurations - tăng 27% từ 2023.

Xu hướng chính:

  1. Hybrid Headless: Kết hợp traditional CMS với headless flexibility
  2. AI Integration: AI-powered content creation và management
  3. Performance First: Core Web Vitals trở thành ranking factor quan trọng
  4. Edge Computing: Deploy frontend ở edge cho global performance

Kết luận#

SPA và WordPress không thực sự là công nghệ cạnh tranh - chúng phục vụ mục đích khác nhau:

  • WordPress Truyền thống: Cho content-heavy sites với non-technical editors
  • SPA: Cho complex applications với high interactivity
  • Headless WordPress: Khi cần cả sophisticated application frontend và easy content management

Key takeaway: Chọn kiến trúc dựa trên requirements của project, không phải dựa trên hype hoặc trend. Đôi khi giải pháp hybrid tốt nhất là kết hợp cả hai.

Tài liệu tham khảo#