Bỏ qua đến nội dung

Usecase: Migrate Vite → Next.js 16 Song Song

Đây là usecase thực tế được thực hiện bằng Claude Code + Superpowers. Nội dung dưới đây mô tả lại quá trình từ brainstorm đến hoàn thành, bao gồm cả phần redesign UI sau migration.

Migrate một ứng dụng React từ Vite sang Next.js 16 không phải là việc của một agent làm tuần tự. Superpowers cho phép bạn brainstorm chiến lược, viết plan chi tiết, và dispatch nhiều agent song song — mỗi agent sở hữu files riêng, không conflict.


Bối Cảnh

Dự án là một ứng dụng Todo App với tính năng đăng nhập, được viết bằng React 19 + Vite 7. Đây là stack hiện tại:

Khía cạnhChi tiết
FrameworkReact 19 + Vite 7 (SPA, không có routing)
Ngôn ngữTypeScript 5.9 (strict mode)
UITailwind CSS 4 + shadcn/ui
StateContext API + useReducer
BackendKhông có — 100% localStorage
AuthClient-side SHA-256 hash, lưu localStorage
FeaturesTodo CRUD, Drag-drop, Filters, Dark mode, Auth
TestingVitest + React Testing Library

Mục tiêu: Migrate toàn bộ sang Next.js 16 App Router, giữ nguyên logic hiện tại (localStorage, client-side auth, UI libraries). Team có 3-4 agent có thể làm song song.

Yêu cầu quan trọng:

  • Chỉ thay đổi framework, không thay đổi logic
  • Tất cả test hiện tại vẫn phải pass sau khi migrate
  • Nhiều agent có thể làm việc cùng lúc trên các files khác nhau

Bạn Sẽ Học Được Gì

Sau khi đọc xong usecase này, bạn sẽ biết cách áp dụng các kỹ thuật Superpowers vào một tình huống refactor/migration thực tế:

  1. Brainstorming chiến lược migration — hỏi đúng câu hỏi, đề xuất approaches, và chọn hướng tối ưu
  2. Viết Kế Hoạch cho công việc song song — chia task theo phase với dependency rõ ràng
  3. Parallel Subagents để thực thi đồng thời — 3 agent làm việc cùng lúc trên các files riêng biệt
  4. Two-Stage Code Review để đảm bảo chất lượng — spec review tự động sau mỗi phase
  5. Verification để xác minh kết quả — build + test phải pass trước khi tiếp tục

Từng Bước Thực Hành

Bước 0: Brainstorm Chiến Lược Migration

Trước khi viết plan, bạn cần brainstorm để xác định chiến lược. Bạn mở chat với AI và nói:

"Tôi cần refactor toàn bộ dự án này thành NextJS 16, đây là một dự án web todo có tài khoản đăng nhập. Team có 3-4 agent có thể làm song song. Hãy brainstorm chiến lược refactor trước khi bắt đầu."

AI vào chế độ brainstorm (sử dụng skill superpowers:brainstorming), khám phá codebase, rồi bắt đầu hỏi từng câu hỏi:

AI: "Phạm vi refactor này đến đâu ạ?"

  • A) Full-stack — Thêm database thật, API routes, authentication server-side
  • B) Hybrid — Server Components + App Router cho rendering, nhưng giữ localStorage
  • C) Framework migration only — Chuyển từ Vite sang Next.js 16, giữ nguyên logic

Chọn: C) Framework migration only — tập trung vào cấu trúc project và routing.

AI: "Về routing, cấu trúc URL như thế nào?"

  • A) Minimal routing — Chỉ 2 routes: / (todo app) và /login (auth page)
  • B) Structured routing — Nhiều routes: /login, /register, /todos, /todos/[id]

Chọn: A) Minimal routing — đơn giản, gần giống hiện tại nhất.

AI: "Các thư viện UI hiện tại giữ nguyên hay thay đổi?"

Chọn: Giữ nguyên tất cả — shadcn/ui, @dnd-kit, sonner, date-fns, lucide-react.

AI: "Testing dùng framework nào?"

  • A) Giữ Vitest — Next.js 16 hỗ trợ natively
  • B) Chuyển sang Jest

Chọn: A) Giữ Vitest.

AI: "Về deployment, target cụ thể nào không?"

  • A) Vercel — Tối ưu nhất cho Next.js, zero config
  • B) Self-hosted / Docker
  • C) Chưa quan tâm — Tính sau, giờ tập trung migrate

Chọn: C) Chưa quan tâm — tập trung migrate trước.

Sau khi thu thập đủ thông tin, AI trình bày 3 hướng tiếp cận:

## Approach A: Scaffold mới + Migrate từng phần (Recommended)
Tạo project Next.js 16 mới, copy/adapt từng phần sang.
- Pros: Clean structure, dễ phân chia agents song song, project chạy được ngay từ đầu
- Cons: Cần setup lại config (shadcn, tailwind)

## Approach B: In-place migration
Chuyển đổi ngay trên project hiện tại — thay Vite bằng Next.js.
- Pros: Không mất git history
- Cons: Dễ conflict, project không chạy được giữa chừng, khó chia task song song

## Approach C: Codemods + tự động hóa
Dùng @next/codemod và script để tự động chuyển đổi.
- Pros: Nhanh cho phần cơ bản
- Cons: Codemods không cover Vite → Next.js, project nhỏ nên overkill

## Khuyến nghị
Approach A. Project nhỏ (~15 components), scaffold mới nhanh hơn migrate in-place.
Dễ phân chia cho 3-4 agents song song.

Chọn Approach A. AI hỏi thêm: "Anh có muốn em hiển thị diagrams và mockups trên browser không?" → Đồng ý. AI khởi động visual companion (một local server) để render architecture diagrams trực tiếp trên trình duyệt.

AI tiếp tục trình bày design chi tiết qua 5 section (hiển thị trên browser):

  1. Project Structure — Cấu trúc thư mục mới với App Router (app/, components/, hooks/, lib/, types/, contexts/)
  2. Component Mapping — Phân loại Server vs Client Components. Pattern: Thin Server Shell → Fat Client Tree
  3. Routing & Auth Flow/ wrap trong AuthGuard, /login redirect nếu đã đăng nhập, dùng next/navigation
  4. Agent Parallelization — 3 phases: Foundation → Parallel Features → Integration
  5. Migration Details — Package thêm/bớt, config changes, import paths

AI lưu design spec vào docs/superpowers/specs/ và dispatch spec reviewer tự động. Reviewer phát hiện 3 issues (thiếu todo-app.tsx orchestrator, test directory structure, Toaster placement) → AI fix → reviewer approve lần 2.

Lưu ý Superpowers: Design spec được lưu vào docs/superpowers/specs/ và review trước khi viết plan. Xem thêm Brainstorming.


Bước 1: Superpowers Viết Plan Phân Chia Tasks

Trước khi bất kỳ dòng code nào được viết, AI sẽ tạo một plan chi tiết (sử dụng skill superpowers:writing-plans). Đây là nguyên tắc cốt lõi: không có plan thì không có execution.

AI đọc tất cả source files, rồi tạo plan với 10 tasks chia thành 3 phases:

Phase 1: Foundation (1 agent, tuần tự — phải xong trước)

  1. Task 1: Scaffold Next.js 16 project mới với create-next-app
  2. Task 2: Thêm dependencies và config (Tailwind, shadcn, Vitest, tsconfig)
  3. Task 3: Copy unchanged files (lib/, types/, hooks/, contexts/, components/ui/)
  4. Task 4: Tạo app/layout.tsx — Root layout với AuthProvider và Toaster
  5. Task 5: Tạo app/globals.css — Migrate CSS từ src/index.css

Phase 2: Features (3 agents song song)

  1. Task 6 — Agent Auth: Tạo auth pages (auth-guard.tsx, auth-page.tsx, login-form.tsx, register-form.tsx, app/login/page.tsx)
  2. Task 7 — Agent Todo: Tạo todo page (todo-app.tsx, header.tsx, filter-bar.tsx, todo-list.tsx, todo-item.tsx, todo-input.tsx, edit-todo-dialog.tsx, app/page.tsx)
  3. Task 8 — Agent Test: Migrate 8 test files sang __tests__/, update relative imports → @/ alias

Phase 3: Integration (1 agent, tuần tự)

  1. Task 9: Chạy npm run build + npx vitest run, fix mọi issues
  2. Task 10: Cleanup và final commit

Đồ thị phụ thuộc:

Phase 1 (Tasks 1-5) ─── sequential ───→ Phase 2 (Tasks 6-8) ─── parallel ───→ Phase 3 (Tasks 9-10)
                                          ├─ Agent Auth (Task 6)
                                          ├─ Agent Todo (Task 7)
                                          └─ Agent Test (Task 8)

Điều kiện tiên quyết cho parallel execution: mỗi agent sở hữu files riêng, không overlap. Agent Auth chỉ sửa auth-related files, Agent Todo chỉ sửa todo-related files, Agent Test chỉ tạo test files.

AI dispatch plan reviewer tự động → reviewer phát hiện 1 issue (test files dùng relative imports sẽ break khi move) → AI fix bằng import mapping table → reviewer approve.

AI hỏi cách thực thi:

"Hai cách thực thi: 1) Subagent-Driven (khuyến nghị) — dispatch agents, review giữa tasks. 2) Inline Execution — thực thi ngay trong session. Chọn cách nào?"

Chọn: 1) Subagent-Driven — phù hợp với yêu cầu 3-4 agents song song.

Bước 2: Phase 1 — Foundation

AI gộp 5 tasks foundation thành 1 agent lớn (vì chúng phụ thuộc tuần tự). Agent thực hiện:

  1. Scaffold: npx create-next-app@latest với TypeScript, Tailwind CSS, App Router
  2. Config: Thêm dependencies (@dnd-kit/*, sonner, date-fns, shadcn, etc.), setup vitest.config.ts, components.json
  3. Copy files: lib/, types/, hooks/, contexts/, components/ui/ — copy nguyên vẹn, chỉ thêm "use client" ở đầu file
  4. Layout: Tạo app/layout.tsx với metadata, fonts, <AuthProvider>, <Toaster />
  5. CSS: Migrate globals.css với Tailwind 4 syntax

Sau khi Phase 1 hoàn tất (7 commits), AI dispatch spec reviewer chạy nền để kiểm tra compliance trong khi chuẩn bị Phase 2.

Phase 1: DONE — 7 commits, build thành công, tất cả files đúng vị trí

Bước 3: Dispatch 3 Agents Song Song (Phase 2)

Khi Phase 1 xong, controller dispatch 3 agents đồng thời:

AgentTaskFiles sở hữu
Auth AgentAuth pages + route protectionauth-guard, auth-page, login-form, register-form, app/login/page.tsx
Todo AgentTodo page + all componentstodo-app, header, filter-bar, todo-list, todo-item, todo-input, edit-todo-dialog, app/page.tsx
Test AgentMigrate 8 test files__tests__/components/, __tests__/contexts/, __tests__/hooks/, __tests__/lib/

Mỗi agent nhận được:

  • Scope rõ ràng: danh sách files cụ thể từ plan
  • Spec reference: link đến design spec để biết component cần adapt như thế nào
  • Constraint: không sửa file ngoài scope, thêm "use client" ở đầu mỗi interactive component

Diễn biến thực tế:

  • Auth Agent hoàn tất đầu tiên — 5 files, TypeScript pass, commit 740e5dd. IDE báo lỗi todo-list.tsx import ./todo-item — nhưng đây là do Todo Agent chưa tạo xong file, sẽ tự resolve.

  • Todo Agent hoàn tất tiếp theo — 8 files, TypeScript pass, commit 55a8988. Tạo todo-app.tsx mới làm orchestrator (extract logic từ App.tsx), wrap trong <AuthGuard>.

  • Test Agent hoàn tất cuối cùng — tạo xong 8 test files nhưng không thể chạy tests/commit do thiếu permissions. Controller chạy npx vitest run và commit thay — 39/39 tests PASS.

Auth Agent: DONE — 5 files, TypeScript pass
Todo Agent: DONE — 8 files, TypeScript pass
Test Agent: DONE — 8 test files migrated, 39/39 tests pass

Bước 4: Phase 3 — Integration Verification

Khi cả 3 agents hoàn tất, controller chạy integration:

npm run build

Build fail! Lỗi: window is not defined — xảy ra vì useThemeuseTodos truy cập window/localStorage trong useState initializer. Đây là SSR prerendering issue đặc thù của Next.js (Vite không có).

Fix: Thêm SSR guard vào hooks:

// hooks/use-theme.ts
const [theme, setTheme] = useState<'light' | 'dark'>(() => {
  if (typeof window === 'undefined') return 'light' // SSR guard
  const saved = loadTheme()
  if (saved) return saved
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
})

// hooks/use-todos.ts
const [todos, dispatch] = useReducer(todoReducer, [], () => {
  if (typeof window === 'undefined') return [] // SSR guard
  return loadTodos()
})

Chạy lại: npm run buildBuild thành công! npx vitest run39/39 tests PASS!

Bài học thực tế: Khi migrate từ SPA (Vite) sang framework có SSR (Next.js), luôn guard browser-only APIs (window, localStorage, document) trong initial state. Đây là issue phổ biến nhất.

Bước 5: Verification Gate

Trước khi tuyên bố migration hoàn thành:

1. CHẠY

npm run build && npx vitest run

2. ĐỌC

✓ Compiled successfully
Routes:
  ○ /           — Static
  ○ /login      — Static
  ○ /_not-found — Static

Test Suites: 8 passed, 8 total
Tests:       39 passed, 39 total

3. XÁC NHẬN

MetricKết quả
Buildnext build thành công
Tests39/39 pass (8 test files)
Routes/ (todo app), /login (auth)
Commits11 commits sạch sẽ

4. GIT HISTORY

050db4f chore: add .superpowers/ to .gitignore
edfa697 fix: guard window/localStorage access for SSR prerendering
97542b0 test: migrate all test files to __tests__/ directory
55a8988 feat: add todo page with all components
740e5dd feat: add auth pages with client-side route protection
76abbff fix: add "use client" to sonner component, accept Next.js tsconfig updates
e78ce06 feat: add root layout with AuthProvider and Toaster
65ff090 chore: copy unchanged source files
451ad1d chore: configure TypeScript, Vitest, and shadcn
a50080f chore: add project dependencies
bb0f5c5 chore: scaffold Next.js 16 project

Bonus: Neo Brutalism Redesign (Song Song Tiếp Theo)

Sau khi migration hoàn tất và được verify, team tiếp tục với một yêu cầu mới: redesign toàn bộ UI theo phong cách Neo Brutalism. Quy trình Superpowers lặp lại y hệt:

Brainstorm Neo Brutalism

AI hỏi 5 câu hỏi:

  1. Mức độ brutal → Chọn: Bold Neo Brutalism (border đen 3px, shadow cứng, màu rực rỡ)
  2. Color palette → Chọn: Candy Crush (hồng/tím/xanh — #FF85A1, #A855F7, #38BDF8)
  3. Scope → Chọn: Toàn bộ (cả login và todo page)
  4. Dark mode → Chọn: Giữ cả hai (light Neo Brutalism chính, dark adapted)
  5. Font → Chọn: Space Grotesk (geometric sans-serif phổ biến trong Neo Brutalism)

AI đề xuất 3 approaches → Chọn CSS-first (thay đổi qua CSS variables + Tailwind classes, giữ nguyên component structure, tests vẫn pass).

Plan Neo Brutalism: 6 Tasks, 4 Phases

PhaseTasksAgentsMô tả
1: FoundationTask 11Font swap, CSS variables, utility classes
2: Base UITask 21button, input, dialog, select, dropdown, popover, sonner, calendar
3: ComponentsTask 3-53 song songAuth (A), Layout (B), Items (C)
4: IntegrationTask 61Build, tests, visual check

Execution Song Song

Phase 1+2 (gộp 1 agent vì phụ thuộc tuần tự):

  • Đổi font Geist → Space Grotesk
  • Thay toàn bộ CSS variables (colors OKLch → Candy Crush palette)
  • Thêm utility classes: .brutal-shadow, .brutal-border, hover/active transforms
  • Update shadcn/ui base components (button, input, dialog, select...)

Phase 3 — 3 agents song song:

AgentFiles
Agent A: Authauth-page, login-form, register-form
Agent B: Layoutheader, filter-bar, todo-list
Agent C: Itemstodo-item, todo-input, edit-todo-dialog

Phase 4: Build + Test → 39/39 tests vẫn pass (vì chỉ thay đổi styling, không đụng logic).

Kết quả Neo Brutalism

  • Font: Geist → Space Grotesk Variable
  • Colors: OKLch neutral → Candy Crush (pink/purple/blue)
  • Borders: 1px transparent → 3px solid black
  • Shadows: Soft blur → Hard 4px offset (no blur)
  • Hover/Active: Lift up / Push down transforms
  • Dark mode: Navy background, colored borders, bold colors preserved
  • 5 commits cho toàn bộ redesign

Kết Quả Tổng Thể

Sau khi hoàn thành cả migration và redesign:

MetricTrướcSau
FrameworkReact 19 + Vite 7 (SPA)Next.js 16 App Router
RoutingKhông có (toggle state)//login với next/navigation
ComponentsTất cả client-sideServer shells + Client components
StyleDefault shadcn/uiBold Neo Brutalism (Candy Crush)
FontGeistSpace Grotesk
Tests39 pass39 pass (không break)
Commits11 (migration) + 5 (redesign) = 16 commits
  • 0 test bị break — logic giữ nguyên 100%
  • Thời gian giảm đáng kể nhờ parallel execution (3 agents Phase 2 migration + 3 agents Phase 3 redesign)
  • Issues thực tế được fix on-the-fly: SSR window guard, "use client" directive cho sonner, test import paths

Key Takeaways

  1. Brainstorm trước khi code. Hỏi đúng câu hỏi (scope, approach, constraints) giúp tránh refactor sai hướng. Trong case này, 5 câu hỏi brainstorm đã xác định rõ: "framework migration only, scaffold mới, giữ nguyên logic".

  2. Plan chi tiết là điều kiện tiên quyết cho parallel execution. Plan phải chỉ rõ: ai làm gì, files nào, dependency giữa các tasks. Nếu không chia rõ file ownership, agents sẽ conflict.

  3. Chia phase theo dependency, song song trong mỗi phase. Foundation phải xong trước (scaffold, config), rồi mới dispatch agents song song cho features. Đây là pattern: Sequential Phases → Parallel Tasks Within Phase.

  4. Spec và plan đều được review tự động. AI dispatch reviewer agent sau khi viết spec/plan. Reviewer phát hiện issues (thiếu orchestrator component, sai test import paths) trước khi execution bắt đầu — sửa rẻ hơn nhiều so với sửa sau khi code.

  5. Issues thực tế luôn xuất hiện. Trong case này, SSR window is not defined là issue đặc thù khi migrate SPA → SSR framework. Integration phase (Phase 3) tồn tại để catch và fix những issues này.

  6. Quy trình lặp lại được. Sau khi migration xong, redesign Neo Brutalism đi theo đúng quy trình: brainstorm → spec → plan → parallel execution → verify. Cùng pattern, khác context.


Tóm tắt: Migrate một ứng dụng React/Vite sang Next.js 16 + redesign Neo Brutalism trong cùng một session. Superpowers orchestrate toàn bộ: brainstorm xác định chiến lược, plan chia task theo phase, parallel agents thực thi đồng thời, spec review đảm bảo chất lượng, và verification gate catch issues trước khi tuyên bố hoàn thành. Kết quả: 16 commits, 39/39 tests pass, 0 regression.