Thêm tính năng vào dự án
Hướng dẫn này sẽ chỉ bạn cách sử dụng Galaxy CLI để thêm authentication vào một Next.js app đã có sẵn.
Tình huống
Phần tiêu đề “Tình huống”Giả sử bạn đã có một Next.js blog app với:
- Post listing
- Post detail pages
- Basic routing
Bây giờ bạn muốn thêm:
- User authentication (sign up, sign in)
- Protected admin panel
- Author information cho posts
Bước 1: Mở dự án
Phần tiêu đề “Bước 1: Mở dự án”-
Navigate đến thư mục dự án
Terminal window cd ~/projects/my-blog -
Kiểm tra cấu trúc hiện tại
Terminal window tree -L 2# Output:# .# ├── app/# │ ├── page.tsx# │ ├── posts/# │ └── layout.tsx# ├── components/# │ └── PostCard.tsx# └── package.json -
Khởi động Galaxy CLI
Terminal window cd /path/to/galaxy-clibun run start
Bước 2: Phân tích dự án hiện tại (Optional)
Phần tiêu đề “Bước 2: Phân tích dự án hiện tại (Optional)”Trước khi thêm feature, bạn có thể yêu cầu Galaxy phân tích dự án:
> Phân tích dự án nàyGalaxy sẽ scan và báo cáo:
📊 Phân tích dự án: My Blog App
🏗️ Tech Stack:- Next.js 14 (App Router)- TypeScript- Tailwind CSS
✨ Features hiện có:1. Post Listing - Display all blog posts2. Post Detail - View individual post3. Responsive Layout
📁 Cấu trúc:- app/ - Next.js App Router pages- components/ - Reusable components- lib/ - Utility functions
💡 Đề xuất improvements:1. Thêm authentication system2. Implement comment system3. Add SEO optimization4. Setup analytics
Bạn muốn làm gì với dự án này?Bước 3: Yêu cầu thêm feature
Phần tiêu đề “Bước 3: Yêu cầu thêm feature”> Thêm user authentication với những tính năng sau:- Sign up với email/password- Sign in và sign out- JWT token management- Protected admin panel để tạo/edit posts- Author information hiển thị trên mỗi post- Profile page cho users
Sử dụng NextAuth.js và Prisma để lưu user data.Bước 4: Galaxy phân tích feature request
Phần tiêu đề “Bước 4: Galaxy phân tích feature request”🔄 Đang phân tích yêu cầu...
⚡ ba_it_analyze↳ Analyzing feature requirements...BA Analyzer sẽ output:
📊 Phân tích feature: User Authentication System
Type: update_project (thêm feature vào dự án hiện có)
💡 Mô tả:Hệ thống authentication hoàn chỉnh với NextAuth.js, JWT tokens,và protected routes cho admin panel.
✨ Features cần implement:
1. Authentication Flow (must-have) - Sign up form với validation - Sign in form với remember me - Sign out functionality - Password hashing với bcrypt - JWT token generation & verification
2. Protected Routes (must-have) - Admin panel route protection - Middleware để check authentication - Redirect unauthorized users
3. User Profile (should-have) - Profile page hiển thị user info - Edit profile functionality - Avatar upload
4. Post-Author Integration (must-have) - Link posts với authors - Display author info on posts - Author page với all their posts
📦 Dependencies cần thêm:- next-auth@latest- bcryptjs- @prisma/client (update schema)- jsonwebtoken
📊 Database Changes:- User model: id, email, password, name, image, role- Update Post model: add authorId foreign key
🔗 New API Endpoints:- POST /api/auth/signup - Register user- POST /api/auth/[...nextauth] - NextAuth endpoints- GET /api/user/profile - Get user profile- PUT /api/user/profile - Update profile
⏱️ Thời gian ước tính: Medium (3-5 hours)
Bạn đồng ý với phương án này?Bước 5: Xác nhận và Planning
Phần tiêu đề “Bước 5: Xác nhận và Planning”> yes, làm điGalaxy tạo execution plan:
📋 Implementation Plan (medium):
☐ Step 1: Update Prisma schema Tool: code_generate Reasoning: Add User model và update Post model
☐ Step 2: Install authentication dependencies Tool: install_dependencies Reasoning: NextAuth.js, bcryptjs, etc.
☐ Step 3: Implement Authentication System Tool: code_generate Feature: Authentication Flow (must-have) Reasoning: Sign up, sign in, JWT management
☐ Step 4: Implement Protected Routes Tool: code_generate Feature: Protected Routes (must-have) Reasoning: Admin panel protection với middleware
☐ Step 5: Implement User Profile Tool: code_generate Feature: User Profile (should-have) Reasoning: Profile page và edit functionality
☐ Step 6: Integrate Authors with Posts Tool: code_generate Feature: Post-Author Integration (must-have) Reasoning: Link posts với authors, display author info
Bắt đầu thực thi? (yes/no)Bước 6: Thực thi
Phần tiêu đề “Bước 6: Thực thi”> yesStep 1: Update Prisma schema
Phần tiêu đề “Step 1: Update Prisma schema”⚙ Step 1: Update Prisma schema - In progress...
📝 APPLY PATCH (prisma/schema.prisma)↳ Succeeded. File edited. (+25 added, -2 removed)
8 | model Post { 9 | id String @id @default(cuid()) 10 | title String 11 | content String 12 + authorId String 13 + author User @relation(fields: [authorId], references: [id]) ... 25 + model User { 26 + id String @id @default(cuid()) 27 + email String @unique 28 + password String 29 + name String? 30 + image String? 31 + role Role @default(USER) 32 + posts Post[] 33 + createdAt DateTime @default(now()) 34 + } 35 + 36 + enum Role { 37 + USER 38 + ADMIN 39 + }
⚡ EXECUTE (npx prisma db push)↳ ✓ Success. Database updated.
☒ Step 1: Update Prisma schema - CompletedStep 2: Install dependencies
Phần tiêu đề “Step 2: Install dependencies”⚙ Step 2: Install authentication dependencies - In progress...
⚡ EXECUTE (npm install next-auth bcryptjs @types/bcryptjs)↳ ✓ Success. Installed 3 packages.
☒ Step 2: Install authentication dependencies - CompletedStep 3: Authentication System
Phần tiêu đề “Step 3: Authentication System”⚙ Step 3: Implement Authentication System - In progress...
📝 APPLY PATCH (app/api/auth/[...nextauth]/route.ts)↳ Succeeded. File created. (+78 added)
📝 APPLY PATCH (app/api/auth/signup/route.ts)↳ Succeeded. File created. (+42 added)
📝 APPLY PATCH (app/(auth)/signin/page.tsx)↳ Succeeded. File created. (+95 added)
📝 APPLY PATCH (app/(auth)/signup/page.tsx)↳ Succeeded. File created. (+110 added)
📝 APPLY PATCH (lib/auth.ts)↳ Succeeded. File created. (+35 added)
📝 APPLY PATCH (components/SignInForm.tsx)↳ Succeeded. File created. (+68 added)
📝 APPLY PATCH (components/SignUpForm.tsx)↳ Succeeded. File created. (+82 added)
☒ Step 3: Implement Authentication System - Completed Created 7 filesStep 4: Protected Routes
Phần tiêu đề “Step 4: Protected Routes”⚙ Step 4: Implement Protected Routes - In progress...
📝 APPLY PATCH (middleware.ts)↳ Succeeded. File created. (+28 added)
📝 APPLY PATCH (app/admin/layout.tsx)↳ Succeeded. File created. (+35 added)
📝 APPLY PATCH (app/admin/posts/new/page.tsx)↳ Succeeded. File created. (+120 added)
📝 APPLY PATCH (app/admin/posts/[id]/edit/page.tsx)↳ Succeeded. File created. (+135 added)
☒ Step 4: Implement Protected Routes - Completed Created 4 filesStep 5: User Profile
Phần tiêu đề “Step 5: User Profile”⚙ Step 5: Implement User Profile - In progress...
📝 APPLY PATCH (app/profile/page.tsx)↳ Succeeded. File created. (+85 added)
📝 APPLY PATCH (app/api/user/profile/route.ts)↳ Succeeded. File created. (+45 added)
📝 APPLY PATCH (components/ProfileForm.tsx)↳ Succeeded. File created. (+72 added)
☒ Step 5: Implement User Profile - Completed Created 3 filesStep 6: Post-Author Integration
Phần tiêu đề “Step 6: Post-Author Integration”⚙ Step 6: Integrate Authors with Posts - In progress...
📝 APPLY PATCH (components/PostCard.tsx)↳ Succeeded. File edited. (+15 added, -3 removed)
12 | export function PostCard({ post }: Props) { 13 | return ( 14 | <article className="..."> 15 | <h2>{post.title}</h2> 16 + <div className="flex items-center gap-2 mt-2"> 17 + <Avatar src={post.author.image} /> 18 + <span className="text-sm"> 19 + By {post.author.name} 20 + </span> 21 + </div> ...
📝 APPLY PATCH (app/posts/[id]/page.tsx)↳ Succeeded. File edited. (+20 added, -5 removed)
📝 APPLY PATCH (app/author/[id]/page.tsx)↳ Succeeded. File created. (+65 added)
📝 APPLY PATCH (components/AuthorCard.tsx)↳ Succeeded. File created. (+38 added)
☒ Step 6: Integrate Authors with Posts - Completed Modified 2 files, Created 2 filesBước 7: Hoàn thành
Phần tiêu đề “Bước 7: Hoàn thành”✅ All steps completed!
📊 Summary:- Modified 3 existing files- Created 20 new files- Updated database schema- Added 4 API endpoints- Implemented protected routes
🆕 New Features:✅ User Authentication (Sign up/Sign in)✅ Protected Admin Panel✅ User Profile Management✅ Author Information on Posts
🚀 Next steps:1. Test authentication flow2. Create first admin user3. Setup email verification (optional)4. Add password reset (optional)
📁 Modified files:- prisma/schema.prisma- components/PostCard.tsx- app/posts/[id]/page.tsx
📄 Progress saved: .galaxy/progress.jsonKiểm tra kết quả
Phần tiêu đề “Kiểm tra kết quả”-
Restart development server
Terminal window npm run dev -
Test Sign Up
- Truy cập http://localhost:3000/signup
- Đăng ký tài khoản mới
- Kiểm tra redirect sau khi sign up
-
Test Sign In
- Truy cập http://localhost:3000/signin
- Đăng nhập với account vừa tạo
- Verify JWT token được set
-
Test Protected Routes
- Truy cập http://localhost:3000/admin
- Nếu chưa login → redirect về /signin
- Nếu đã login → vào được admin panel
-
Test Author Integration
- Browse posts → see author info
- Click vào author name → author page
- Verify posts grouped by author
So sánh Before vs After
Phần tiêu đề “So sánh Before vs After”my-blog/├── app/│ ├── page.tsx│ ├── posts/│ │ └── [id]/page.tsx│ └── layout.tsx├── components/│ └── PostCard.tsx└── package.jsonFeatures:
- Post listing
- Post detail pages
my-blog/├── app/│ ├── page.tsx│ ├── posts/│ ├── (auth)/│ │ ├── signin/│ │ └── signup/│ ├── admin/ # ✨ NEW│ │ ├── layout.tsx│ │ └── posts/│ ├── profile/ # ✨ NEW│ ├── author/ # ✨ NEW│ └── api/│ ├── auth/ # ✨ NEW│ └── user/ # ✨ NEW├── components/│ ├── PostCard.tsx # ✨ MODIFIED│ ├── SignInForm.tsx # ✨ NEW│ ├── SignUpForm.tsx # ✨ NEW│ ├── ProfileForm.tsx # ✨ NEW│ └── AuthorCard.tsx # ✨ NEW├── middleware.ts # ✨ NEW├── lib/│ └── auth.ts # ✨ NEW└── prisma/ └── schema.prisma # ✨ MODIFIEDFeatures:
- Post listing
- Post detail pages
- ✨ User authentication
- ✨ Protected admin panel
- ✨ User profiles
- ✨ Author pages
Tips cho việc thêm features
Phần tiêu đề “Tips cho việc thêm features”Troubleshooting
Phần tiêu đề “Troubleshooting”Lỗi: NextAuth session not working
Phần tiêu đề “Lỗi: NextAuth session not working”// Check app/layout.tsx có wrap với SessionProvider chưaimport { SessionProvider } from 'next-auth/react';
export default function RootLayout({ children }) { return ( <SessionProvider> {children} </SessionProvider> );}Lỗi: Protected routes not working
Phần tiêu đề “Lỗi: Protected routes not working”// Check middleware.ts có config đúng chưaexport const config = { matcher: ['/admin/:path*', '/profile/:path*']};Lỗi: Author not showing on posts
Phần tiêu đề “Lỗi: Author not showing on posts”// Ensure query includes author relationconst post = await prisma.post.findUnique({ where: { id }, include: { author: true } // ← Include this});Tiếp theo thêm features gì?
Phần tiêu đề “Tiếp theo thêm features gì?”Bạn có thể tiếp tục thêm:
# Comment system> Thêm comment system cho posts với nested replies
# Social sharing> Thêm social sharing buttons (Twitter, Facebook, LinkedIn)
# Email notifications> Thêm email notifications khi có comment mới
# Search functionality> Implement full-text search cho postsCác bước tiếp theo
Phần tiêu đề “Các bước tiếp theo”- Analyze Project - Phân tích dự án chi tiết
- Workflow - Hiểu luồng hoạt động
- Tools Reference - Tìm hiểu tools có sẵn