全棧身份認證實作:使用 Next.js、NextAuth.js 和 MongoDB-10. 用戶資料更新
Published in
Dec 13, 2023
實現用戶資料的更新,包括創建表單和處理更新請求。
10–1. 建立用戶資料更新頁面
- 在 lib/validations/auth.ts 中新增 userUpdateValidation 來驗證用戶輸入。
- 於 components/form 資料夾建立 UpdateForm 組件(update-form.tsx)。
- app/(auth) 資料夾中建立 profile 資料夾,存放對應頁面(page.tsx),import UpdateForm。
10–2. 設定用戶資料更新功能
- 在 auth.actions.ts 中新增 updateUserProfile 以處理用戶更新請求,檢查用戶登入狀態,並在資料庫中更新用戶信息,在更新成功時顯示成功通知,若發生錯誤則導向錯誤頁面,並顯示相應錯誤信息。
- 在 “use client” 組件使用 server action 的方式:在 use server 頁面(ProfilePage)將 server action(updateUserProfile)作為 props 傳給 use client 組件(UpdateForm),在 auth.actions.ts 中加上 “use server”。
- 為解決在提取 session 中的 user 資料時遇到的類型問題,新增 types 資料夾,並創建 next-auth.d.ts 來定義相關的 TypeScript 類型。
- 在 nextauth-options.ts 中修改 jwt() callback,加上 update trigger,以實現對 session 中 user name 的即時更新。
程式碼
10–3. Toast 通知及錯誤頁面
- 在 layout.ts (RootLayout) 添加 Toaster 組件以顯示通知。
- app 資料夾中新增 error 資料夾,用於存放自定義的錯誤頁面(page.tsx),使用 useSearchParams 從 URL 中獲取錯誤信息並顯示,於 nextauth-options.ts 加上指定的錯誤頁面(error: “/error”)。
程式碼
單元重點:
- (auth) 資料夾中,建立 profile 路徑內容,並且將當中會使用到”use client” 的表單獨立成 UpdateForm 組件。
- 新增 server actions:updateUserProfile。
- 新增 types/next-auth.d.ts 定義相關的 TypeScript 類型。
- nextauth-options.ts 中修改 jwt() callback,加上 update trigger。
- 在 layout.ts (RootLayout) 添加 Toaster,使用 toast 通知。
- 建立 error 路徑內容,於 nextauth-options.ts 加上指定的錯誤頁面。