Le Duy Khuong

Chuỗi: seo-cloudflare · Phần 3

Năng suất & công cụ dev

Managed Features & Gotchas

SSL, caching, gotchas

2026-03-207 phút đọcVI

Managed Features & Gotchas

Mở đầu

Cloudflare Pages quản lý nhiều thứ tự động: SSL certificates, compression, caching, DDoS protection. Đây là lợi ích — nhưng cũng tạo "gotchas" khi deploy Next.js static export. Bài cuối cùng trong toàn bộ 22-article series sẽ cover managed features, known issues, và troubleshooting.

Mục tiêu: Hiểu những gì CF Pages làm tự động, gotchas đặc thù cho Next.js static export, và checklist trước/sau deploy.


Managed Features — CF Pages tự làm

1. SSL/TLS

User → HTTPS → Cloudflare (SSL termination) → Internal → CF Storage
  • Auto SSL cert — Cloudflare issue cert tự động cho custom domain
  • Full (Strict) mode — End-to-end encryption
  • Auto renewal — Cert renew trước khi expire
  • HTTP → HTTPS redirect — Tự động redirect

SEO impact: Google prefers HTTPS. Auto SSL = always HTTPS = SEO benefit.

2. Compression

CF Pages tự động compress response:

FormatSupportReduction
Brotli✅ (default)~60-80%
Gzip✅ (fallback)~50-70%

Browser gửi Accept-Encoding: br, gzip → CF Pages respond với Brotli (nhỏ hơn gzip). Không cần config.

3. Caching

First request: CF Storage → Edge PoP (cache) → User (200, MISS)
Second request: Edge PoP cache → User (200, HIT, <10ms)

Static assets (HTML, JS, CSS, images) cached tại edge. cf-cache-status header cho biết:

  • HIT — Served from cache
  • MISS — Fetched from origin, now cached
  • DYNAMIC — Not cacheable

4. DDoS Protection

CF Pages inherits Cloudflare's DDoS mitigation — free, always-on, no config.

5. HTTP/2 & HTTP/3

Auto-enabled. Multiplexing, header compression, QUIC protocol.


Gotchas — Next.js Static Export + CF Pages

Gotcha 1: Trailing Slash Behavior

Next.js static export outputs:

out/
├── vi/
│   ├── blog/
│   │   ├── learning-in-public.html
│   │   └── index.html
│   └── index.html
└── index.html

CF Pages handles:

  • /vi/blog/learning-in-public → serves learning-in-public.html
  • /vi/blog/learning-in-public/ → serves learning-in-public.html ✅ (trailing slash stripped)

Potential issue: Nếu canonical URL có trailing slash nhưng actual URL không (hoặc ngược lại) → Google thấy 2 URLs → duplicate content.

Fix: Đảm bảo canonical URL consistent (không trailing slash):

canonical: `${BASE_URL}/${locale}/blog/${slug}`, // no trailing slash

Gotcha 2: 404 Page

Next.js static export tạo 404.html. CF Pages tự serve file này cho 404 requests. Nhưng:

  • CF Pages trả status 200 (không phải 404) cho custom 404 page trong một số configs
  • Googlebot cần thấy status 404 để biết page không tồn tại

Verify:

curl -I https://leduykhuong.com/nonexistent-page
# → Check: HTTP/2 404? or 200?

Gotcha 3: SPA Fallback vs Static Routes

CF Pages có "SPA mode" — redirect all 404s to /index.html. Đây là WRONG cho static export (mỗi page có HTML riêng).

Verify: Không enable SPA mode trong CF Pages settings. Mỗi route phải trả đúng HTML file.

Gotcha 4: Cache Invalidation sau Deploy

Khi deploy mới, CF Pages:

  • Tự invalidate cache cho files đã thay đổi
  • Nhưng edge caches có thể giữ old version vài phút

Verify sau deploy:

# Check cf-ray header (unique per response)
curl -I https://leduykhuong.com 2>&1 | grep cf-ray
 
# Wait 1-2 minutes → check again
# cf-ray should change = new content served

Gotcha 5: _next/ Directory Caching

Static export output:

out/
├── _next/
│   └── static/
│       ├── chunks/
│       └── css/

_next/static/ files có content hash trong filename (ví dụ: page-abc123.js). CF Pages cache chúng aggressively (immutable content). Nhưng robots.txt disallow /_next/:

Disallow: /_next/

Trade-off: Google không crawl _next/ (đúng — không cần index JS bundles), nhưng files vẫn load bình thường cho users (robots.txt chỉ ảnh hưởng crawlers, không ảnh hưởng browsers).


Pre-Deploy Checklist

Trước mỗi deploy, verify:

□ npm run build — Build thành công?
□ Check out/sitemap.xml — URLs đúng domain?
□ Check out/robots.txt — Sitemap URL đúng?
□ Check out/index.html — Title, description correct?
□ Check random blog post HTML — Canonical, OG, Twitter tags?
□ Check JSON-LD — BlogPosting, BreadcrumbList present?
□ Check .env.local — Production values set?
□ Grep for localhost — Không có http://localhost trong output?
# Quick pre-deploy verification
npm run build && \
  grep -r 'localhost' out/ --include="*.html" | head -5 && \
  head -3 out/sitemap.xml && \
  grep '<title>' out/index.html

Post-Deploy Checklist

Sau deploy:

□ curl -I https://leduykhuong.com — Status 200?
□ cf-cache-status header present?
□ SSL cert valid (padlock icon)?
□ GSC URL Inspection — "Request Indexing" cho bài mới
□ Facebook Debugger — "Scrape Again" cho updated pages
□ Lighthouse SEO audit — Score OK?

Cloudflare Web Analytics vs GA4

CF Pages tích hợp Cloudflare Web Analytics — privacy-focused analytics:

// app/layout.tsx — CF Analytics script
{process.env.NODE_ENV === "production" &&
  process.env.NEXT_PUBLIC_CF_ANALYTICS_TOKEN && (
    <Script
      defer
      src="https://static.cloudflareinsights.com/beacon.min.js"
      data-cf-beacon={`{"token": "${process.env.NEXT_PUBLIC_CF_ANALYTICS_TOKEN}"}`}
      strategy="afterInteractive"
    />
  )}
FeatureCF Web AnalyticsGA4
PrivacyNo cookies, GDPR-compliantRequires consent
DataBasic (views, visits, referrers)Comprehensive
Free
Setup1 script taggtag.js + config

leduykhuong.com dùng CẢ HAI: CF Analytics cho quick overview (no cookie consent needed), GA4 cho deep analysis.


Troubleshooting Common Issues

Issue: Page content stale sau deploy

# Force cache purge via Cloudflare API
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache" \
  -H "Authorization: Bearer {api_token}" \
  -H "Content-Type: application/json" \
  --data '{"purge_everything":true}'

Hoặc: CF Dashboard → Caching → Purge Everything.

Issue: OG image not updating trên social

Social platforms cache OG images aggressively. Sau khi update OG image:

  1. Facebook: developers.facebook.com/tools/debug/ → "Scrape Again"
  2. LinkedIn: linkedin.com/post-inspector/ → re-fetch
  3. Twitter: Cards tự refresh trong 1-2 ngày

Static export cần actual HTML files cho mỗi route. Nếu route thiếu trong generateStaticParams() → no HTML → 404.

# Verify all expected pages exist
ls out/vi/blog/ | wc -l
# → Should match number of blog posts

Issue: Analytics not loading

# Check if GA4 script present
grep 'googletagmanager' out/index.html
# → Should find gtag.js URL
 
# Check if PostHog present
grep 'posthog' out/index.html
# → Should find posthog-js reference

Nếu không thấy → env vars rỗng khi build. Check .env.local.


Thực hành

Bài tập 1: Full deploy cycle

cd ACE-component/ACE-leduykhuong-site
npm run build
# Run pre-deploy checklist
grep -c '<loc>' out/sitemap.xml
grep 'canonical' out/vi/blog/learning-in-public.html
grep 'og:image' out/vi/blog/learning-in-public.html

Bài tập 2: Cache behavior

# First request
curl -s -o /dev/null -w "Status: %{http_code}, TTFB: %{time_starttransfer}s\n" \
  https://leduykhuong.com
 
# Headers
curl -I https://leduykhuong.com 2>&1 | grep -E 'cache|cf-ray|age'

Bài tập 3: Compare analytics scripts

Mở leduykhuong.com → F12 → Network:

  • Filter: gtag → GA4 loaded?
  • Filter: posthog → PostHog loaded?
  • Filter: beacon → CF Analytics loaded?
  • Bao nhiêu analytics scripts total?

Tóm tắt

  • CF Pages managed features — SSL, compression, caching, DDoS, HTTP/2-3 — tất cả tự động
  • Gotchas — Trailing slash, 404 status code, cache invalidation, SPA mode (disable it)
  • Pre-deploy checklist — Build, verify sitemap/canonical/OG, check env vars, grep localhost
  • Post-deploy checklist — Status 200, cache working, SSL valid, GSC re-index
  • CF Web Analytics — Privacy-focused complement to GA4, no cookies
  • Triple analytics — CF Analytics (overview) + GA4 (marketing) + PostHog (product)

Kết thúc Series

Đây là bài cuối cùng trong 22-article training series v7.1 SEO & Analytics Tools. Toàn bộ series cover:

  1. Next.js Metadata (4 bài) — Metadata API, OG/Twitter, Sitemap/Robots, Debugging
  2. JSON-LD Structured Data (4 bài) — Schema.org, BlogPosting, Multi-Schema, Extending
  3. Google Analytics 4 (4 bài) — Architecture, Reports, Custom Events, GSC Integration
  4. PostHog Product Analytics (4 bài) — vs GA4, Session Replay, Funnels, Feature Flags
  5. Technical SEO (3 bài) — Crawling/Indexing, Sitemap Strategy, Canonical URLs
  6. Cloudflare Pages (3 bài) — Architecture, Env Vars, Managed Features

Tất cả dựa trên code thực tế từ leduykhuong.com — anh có thể mở bất kỳ file nào referenced trong bài và thấy chính xác code đang chạy trên production.

LDK

Le Duy Khuong

AI Transformation & Digital Strategy. Writing about agentic systems, engineering leadership, and building in public.