Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Xác Thực Người Dùng An Toàn Trong Next.js Sử Dụng Auth.js Và Upstash Redis

Trong hướng dẫn này, bạn sẽ học cách triển khai xác thực người dùng trong một ứng dụng Next.js sử dụng Auth.js và Upstash Redis. Bạn sẽ học cách thiết lập môi trường cần thiết, tạo nhà cung cấp xác thực tùy chỉnh để đăng nhập và đăng ký an toàn, và tích hợp Upstash Redis làm cơ sở dữ liệu để quản lý session.

Điều Kiện Tiên Quyết

Bạn sẽ cần những điều sau:

  • Node.js 18 hoặc mới hơn
  • Một tài khoản Upstash

Technology Stack

Công NghệMô Tả
Next.jsThe React Framework for the Web.
UpstashNền tảng cơ sở dữ liệu không máy chủ. Bạn sẽ sử dụng Upstash Redis để quản lý session và thông tin người dùng.

Thiết Lập Instance Upstash Redis

Trong bảng điều khiển Upstash của bạn, chuyển đến tab Redis và tạo một cơ sở dữ liệu.

Xác Thực Người Dùng An Toàn Trong Next.js Sử Dụng Auth.js Và Upstash Redis

Cuộn xuống cho đến khi tìm thấy phần REST API, và chọn nút .env. Sao chép nội dung và lưu ở nơi an toàn.

Xác Thực Người Dùng An Toàn Trong Next.js Sử Dụng Auth.js Và Upstash Redis

Tạo Ứng Dụng Next.js Mới

Hãy bắt đầu bằng cách tạo một dự án Next.js mới. Mở terminal và chạy lệnh sau:

npx create-next-app@latest my-app

Khi được nhắc, hãy chọn:

  • Yes khi được nhắc sử dụng TypeScript.
  • No khi được nhắc sử dụng ESLint.
  • Yes khi được nhắc sử dụng Tailwind CSS.
  • No khi được nhắc sử dụng thư mục src/.
  • Yes khi được nhắc sử dụng App Router.
  • No khi được nhắc sử dụng Turbopack.
  • No khi được nhắc tùy chỉnh alias nhập mặc định (@/*).

Sau khi xong, di chuyển vào thư mục dự án và khởi động ứng dụng ở chế độ phát triển bằng lệnh sau:

cd my-app npm run dev

Ứng dụng sẽ chạy trên localhost:3000. Dừng máy chủ phát triển để cài đặt các phụ thuộc cần thiết bằng các lệnh sau:

npm install @upstash/redis nanoid npm install next-auth @auth/core @auth/upstash-redis-adapter

Các thư viện được cài đặt bao gồm:

  • nanoid: Thư viện tạo ID duy nhất, an toàn.
  • next-auth: Giải pháp xác thực được xây dựng cho Next.js.
  • @auth/core: Gói cốt lõi để xử lý xác thực trong Auth.js.
  • @upstash/redis: SDK để tương tác với Upstash Redis qua các yêu cầu HTTP.
  • @auth/upstash-redis-adapter: Adapter để tích hợp Auth.js với Upstash Redis.

Bây giờ, tạo tệp .env tại thư mục gốc của dự án. Bạn sẽ sử dụng các giá trị AUTH_SECRET, UPSTASH_REDIS_REST_URL và UPSTASH_REDIS_REST_TOKEN.

Tệp .env nên có nội dung sau:

# .env # Auth.js Environment Variable AUTH_SECRET="..." # Upstash Redis Environment Variables UPSTASH_REDIS_REST_URL="https://...upstash.io" UPSTASH_REDIS_REST_TOKEN="..."

Khởi Tạo Client Upstash Redis

Tạo tệp tên redis.ts trong thư mục lib với mã sau:

// File: lib/redis.ts import { Redis } from '@upstash/redis' export default new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, })

Trong mã trên, một instance client Redis tương thích Edge được xuất để sử dụng xuyên suốt ứng dụng.

Thiết Lập Kiểu Người Dụng Và Trợ Giúp Thông Tin Đăng Nhập

Tạo tệp tên types.ts trong thư mục lib với mã sau:

// File: lib/types.ts export interface UserType { id?: string email: string name?: string image?: string password?: string emailVerified?: string }

Interface UserType định nghĩa cấu trúc của đối tượng người dùng trong ứng dụng. Nó bao gồm:

  • id (tùy chọn): Định danh duy nhất cho người dùng.
  • email (bắt buộc): Địa chỉ email của người dùng.
  • name (tùy chọn): Tên của người dùng.
  • image (tùy chọn): URL hoặc đường dẫn đến hình ảnh hồ sơ của người dùng.
  • password (tùy chọn): Mật khẩu đã hash của người dùng.
  • emailVerified (tùy chọn): Dấu thời gian hoặc chuỗi chỉ ra nếu/khi email của người dùng đã được xác minh.

Interface này đóng vai trò là định nghĩa kiểu cho dữ liệu người dùng xuyên suốt ứng dụng.

Tiếp theo, tạo tệp tên credentials.ts trong thư mục lib với mã sau:

// File: lib/credentials.ts export function generateRandomToken() { const array = new Uint8Array(20) crypto.getRandomValues(array) return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('') } export function generateRandomString(inputValue: string) { const encoder = new TextEncoder() const data = encoder.encode(inputValue) return crypto.subtle.digest('SHA-256', data).then((hashBuffer) => { return Array.from(new Uint8Array(hashBuffer)) .map((byte) => byte.toString(16).padStart(2, '0')) .join('') }) } export async function hashPassword(password: string) { const encoder = new TextEncoder() const data = encoder.encode(password) const hashBuffer = await crypto.subtle.digest('SHA-256', data) return Array.from(new Uint8Array(hashBuffer)) .map((byte) => byte.toString(16).padStart(2, '0')) .join('') } export async function comparePassword(password: string, hash: string) { const hashedPassword = await hashPassword(password) return hashedPassword === hash }

Trong mã trên, các hàm tiện ích tương thích Edge để tạo và quản lý token an toàn và mật khẩu đã hash được định nghĩa:

  • generateRandomToken: Tạo một token ngẫu nhiên an toàn mật mã bằng cách tạo mảng ngẫu nhiên 20-byte và chuyển đổi thành chuỗi hex.
  • generateRandomString: Chấp nhận chuỗi đầu vào, mã hóa thành byte, hash bằng SHA-256, và trả về hash dạng hex. Hữu ích để tạo chuỗi duy nhất, nhất quán từ giá trị đầu vào.
  • hashPassword: Hash mật khẩu văn bản thuần túy bằng SHA-256 và chuyển hash kết quả thành chuỗi hex. Được dùng để lưu trữ mật khẩu an toàn.
  • comparePassword: So sánh mật khẩu văn bản thuần túy với mật khẩu đã hash bằng cách hash đầu vào và kiểm tra xem có khớp với hash đã lưu không.

Sử Dụng Adapter Upstash Redis Với Auth.js

Tạo tệp tên auth.ts trong thư mục lib với mã sau:

// File: lib/auth.ts import { UpstashRedisAdapter } from '@auth/upstash-redis-adapter' import NextAuth from 'next-auth' import providers from './providers' import redis from './redis' export const { handlers, signIn, signOut, auth } = NextAuth(() => ({ providers, session: { strategy: 'jwt' }, adapter: UpstashRedisAdapter(redis), }))

Trong mã trên, xác thực được thiết lập bằng cách tạo các hàm handlers, signIn, signOut và auth sử dụng cấu hình tùy chỉnh. Nó sử dụng chiến lược session dựa trên JWT, UpstashRedisAdapter để kết nối với cơ sở dữ liệu Upstash Redis để lưu trữ dữ liệu người dùng, và một mảng các nhà cung cấp xác thực được định nghĩa trong module providers. Thiết lập này cho phép tích hợp liền mạch xác thực và quản lý session với Upstash Redis làm backend.

Thiết Lập Nhà Cung Cấp Xác Thực Tùy Chỉnh Với Auth.js

Tạo tệp tên providers.ts trong thư mục lib với mã sau:

// File: lib/providers.ts import { nanoid } from 'nanoid' import Credentials from 'next-auth/providers/credentials' import { comparePassword, generateRandomString, hashPassword } from './credentials' import redis from './redis' import { UserType } from './types' export default [ Credentials({ credentials: { email: {}, password: {}, }, authorize: async (credentials, request) => { let type try { const tmp = new URL(request.url).searchParams.get('kind') if (tmp && typeof tmp === 'string') type = tmp } catch (e) {} if (!type || !credentials.email || typeof credentials.email !== 'string' || !credentials.password || typeof credentials.password !== 'string') return null const randomizedPassword = await generateRandomString(credentials.password) const userByEmail = await redis.get<string | null | undefined>(`user:email:${credentials.email}`) if (userByEmail) { if (type !== 'in') { console.log(`can not sign in in a non sign-in mode.`) throw new Error(`can not sign in in a non sign-in mode.`) } const user = await redis.get<UserType>(`user:${userByEmail}`) if (!user) { console.log(`Found the user by email from user:email:${userByEmail}, but the user object is missing at user:${userByEmail}`) return null } if (user.password) { const hashedPassword = await hashPassword(randomizedPassword) const isPasswordCorrect = await comparePassword(user.password, hashedPassword) if (isPasswordCorrect) { const { password, ...rest } = user return rest } throw new Error(`incorrect password for credentials.`) } throw new Error(`you are using some other authentication method already, but not credentials.`) } else { if (type !== 'up') { console.log(`can not sign up in a non sign-up mode.`) throw new Error(`can not sign up in a non sign-up mode.`) } const newUser = { name: null, image: null, emailVerified: null, email: credentials.email, password: randomizedPassword, } const tmp = nanoid() await redis.set(`user:email:${credentials.email}`, tmp) await redis.set(`user:${tmp}`, newUser) return newUser } }, }), ]

Trong mã trên, một mảng nhà cung cấp xác thực dựa trên credentials tùy chỉnh được xuất. Nhà cung cấp Credentials xử lý logic đăng nhập và đăng ký: nó kiểm tra xem người dùng có tồn tại trong Redis không và xác thực mật khẩu của họ hoặc tạo người dùng mới. Nếu đăng nhập, nó so sánh mật khẩu được cung cấp (đã hash bằng chuỗi ngẫu nhiên) với mật khẩu đã lưu; nếu đăng ký, nó tạo mục người dùng mới trong Upstash Redis. Mã sử dụng Upstash Redis để lưu trữ dữ liệu người dùng và đảm bảo quy trình được thực hiện ở chế độ đăng ký hoặc đăng nhập dựa trên tham số kind trong URL.

Thiết Lập API Routes Xác Thực (Được Cung Cấp Bởi Auth.js)

Tạo tệp tên route.ts trong thư mục app/api/auth/[...nextauth] với mã sau:

// File: app/api/auth/[...nextauth]/route.ts export const runtime = 'edge' import { handlers } from '@/lib/auth' export const { GET, POST } = handlers

Trong mã trên, hai trình xử lý endpoint GET và POST được xuất, được xử lý bởi hàm handlers được xuất từ tệp @/lib/auth.ts.

Tạo tệp tên route.ts trong thư mục app/api/refresh với mã sau:

// File: app/api/refresh/route.ts export const runtime = 'edge' export const dynamic = 'force-dynamic' export const fetchCache = 'force-no-store' import { auth } from '@/lib/auth' import redis from '@/lib/redis' import { UserType } from '@/lib/types' import { encode } from '@auth/core/jwt' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async function GET(request: Request) { const useSecureCookie = request.url.startsWith('https:') const salt = useSecureCookie ? '__Secure-authjs.session-token' : 'authjs.session-token' if (!process.env.AUTH_SECRET) return new NextResponse(null, { status: 500 }) const [session, cookieStore] = await Promise.all([auth(), cookies()]) if (!session?.user?.email) return new NextResponse(null, { status: 400 }) const userByEmail = await redis.get(`user:email:${session.user.email}`) const userData = await redis.get<UserType>(`user:${userByEmail}`) if (!userData?.email) cookieStore.set(salt, toString(), { secure: useSecureCookie, path: '/', httpOnly: true, sameSite: 'lax', maxAge: 0 }) else { const { image, password, ...rest } = userData const saltVal = await encode({ salt, secret: process.env.AUTH_SECRET, token: { ...rest, picture: image } }) cookieStore.set(salt, saltVal, { secure: useSecureCookie, path: '/', httpOnly: true, sameSite: 'lax' }) } return new NextResponse() }

Trong mã trên, một API route tương thích Edge để làm mới session của người dùng đang được tạo. Nó lấy session người dùng và dữ liệu liên quan từ Redis, xác minh email của người dùng, và cập nhật cookie session. Nếu dữ liệu người dùng không hợp lệ hoặc bị thiếu, cookie session bị xóa; ngược lại, một token đã ký mới được tạo và lưu trong cookie.

Tạo tệp tên route.ts trong thư mục app/api/user với mã sau:

// File: app/api/user/route.ts export const runtime = 'edge' export const dynamic = 'force-dynamic' export const fetchCache = 'force-no-store' import { auth } from '@/lib/auth' import redis from '@/lib/redis' import { UserType } from '@/lib/types' import { NextResponse } from 'next/server' export async function POST(request: Request) { try { const session = await auth() if (!session?.user?.email) return new NextResponse(null, { status: 400 }) const body = await request.json() const userByEmail = await redis.get(`user:email:${session.user.email}`) const userData = await redis.get<UserType>(`user:${userByEmail}`) if (!userData) return new NextResponse(null, { status: 404 }) if (body.name) userData.name = body.name if (body.image) userData.image = body.image await redis.set(`user:${userByEmail}`, userData) return new NextResponse() } catch (e: any) { const message = e.message || e.toString() console.log(message) return new NextResponse(message, { status: 500 }) } }

Trong mã trên, một API route tương thích Edge để cập nhật dữ liệu người dùng đang được tạo. Nó xác thực người dùng, lấy dữ liệu của họ từ Redis bằng email, và cập nhật thông tin của họ (ví dụ: tên hoặc hình ảnh) dựa trên body yêu cầu. Nếu không tìm thấy người dùng hoặc xảy ra lỗi, các mã trạng thái và phản hồi thích hợp được trả về.

Thiết Lập Middleware Next.js Với Auth.js

Tạo tệp tên middleware.ts trong thư mục gốc của dự án với mã sau:

// File: middleware.ts export { auth as middleware } from '@/lib/auth' export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], }

Trong mã trên, middleware được tạo bằng cách xuất lại hàm auth từ module @/lib/auth. Middleware áp dụng xác thực cho tất cả các route trừ API routes, tệp tĩnh, tài sản hình ảnh và favicon, như được chỉ định bởi cấu hình matcher. Điều này đảm bảo các route không bị loại trừ được bảo vệ bởi logic xác thực được thiết lập với Auth.js.

Sử Dụng Auth.js Trong Các Component Next.js App Router

Tạo tệp tên NextAuthProvider.tsx trong thư mục app với mã sau:

// File: app/NextAuthProvider.tsx 'use client' import { SessionProvider } from 'next-auth/react' type Props = { children?: React.ReactNode } export default function ({ children }: Props) { return <SessionProvider>{children}</SessionProvider> }

Trong mã trên, một component React client-side được tạo để bao bọc ứng dụng với SessionProvider của NextAuth. Component chấp nhận children làm props và đảm bảo các component được bao bọc có quyền truy cập vào ngữ cảnh session người dùng do NextAuth cung cấp. Thiết lập này thiết yếu để quản lý trạng thái xác thực xuyên suốt ứng dụng trong Next.js.

Tạo tệp tên csrf.tsx trong thư mục app với mã sau:

// File: app/csrf.tsx 'use client' import { getCsrfToken } from 'next-auth/react' import { useEffect, useState } from 'react' export function CSRFInput() { const [csrfToken, setCsrfToken] = useState<string>() useEffect(() => { getCsrfToken().then((res) => setCsrfToken(res)) }, []) return <input type="hidden" name="csrfToken" defaultValue={csrfToken} /> }

Trong mã trên, một component React client-side được xuất để lấy token CSRF bằng hàm getCsrfToken của NextAuth và lưu nó trong biến state. Component render một trường input ẩn chứa token CSRF, cho phép gửi form an toàn bằng cách bao gồm token làm giá trị ẩn. Điều này hữu ích để bảo vệ khỏi tấn công yêu cầu giả mạo site (CSRF).

Tạo tệp tên provider.tsx trong thư mục app với mã sau:

// File: app/provider.tsx 'use client' import { Button } from '@/components/ui/button' import { Icon } from '@iconify/react' import { signIn } from 'next-auth/react' export default function ({ provider, prefix }: { prefix: string; provider: { name: string; id: string } }) { return ( <Button onClick={() => signIn(provider.id)} key={provider.name} variant="outline" className="flex w-full gap-x-3"> {provider.id === 'google' && <Icon fontSize={18} icon="flat-color-icons:google" />} <span className="text-black"> {prefix} with {provider.name} </span> </Button> ) }

Trong mã trên, một component React để render nút đăng nhập tùy chỉnh cho các nhà cung cấp xác thực khác nhau được xuất. Nó chấp nhận provider (chứa name và id) và prefix làm props. Nút kích hoạt hàm signIn cho nhà cung cấp được chỉ định và hiển thị động icon và nhãn dựa trên id của nhà cung cấp.

Cập nhật tệp tên layout.tsx trong thư mục app với mã sau:

// File: app/layout.tsx import './globals.css' import NextAuthProvider from './NextAuthProvider' export default function ({ children, }: Readonly<{ children: React.ReactNode }>) { return ( <html lang="en"> <body className="bg-white text-black antialiased"> <NextAuthProvider> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col">{children}</div> </NextAuthProvider> </body> </html> ) }

Trong mã trên, layout Next.js bao bọc toàn bộ trang trong các style toàn cục và ngữ cảnh xác thực. Nó nhập globals.css cho style toàn cục và NextAuthProvider để quản lý trạng thái xác thực. Prop children đại diện cho nội dung trang lồng nhau, được bao bọc trong một container có style với padding responsive và chiều rộng tối đa, cung cấp layout nhất quán cho tất cả các trang.

Tải Trạng Thái Xác Thực Người Dụng Trong Trang Client-Side

Cập nhật tệp tên page.tsx trong thư mục app với mã sau:

// File: app/page.tsx 'use client' import { signOut, useSession } from 'next-auth/react' export default function () { const { data, status } = useSession() return ( <> {JSON.stringify({ data, status })} <button onClick={() => signOut()}>Sign Out</button> </> ) }

Trong mã trên, một component React client-side hiển thị dữ liệu session của người dùng và cung cấp nút "Sign Out" được xuất. Nó sử dụng hook useSession của NextAuth để lấy dữ liệu session và trạng thái, hiển thị chúng dưới dạng chuỗi JSON. Hàm signOut được gọi khi nút được nhấp, cho phép người dùng đăng xuất.

Xây Dựng Trang Đăng Nhập Động (Sử Dụng Auth.js)

Tạo tệp tên page.tsx trong thư mục app/signin với mã sau:

// File: app/signin/page.tsx export const runtime = 'edge' import { CSRFInput } from '@/app/csrf' import Provider from '@/app/provider' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { auth } from '@/lib/auth' import providers from '@/lib/providers' import { unstable_noStore } from 'next/cache' import Link from 'next/link' import { redirect } from 'next/navigation' export default async function () { unstable_noStore() const session = await auth() if (session) redirect('/') return ( <div className="border md:border-white/10 flex items-center justify-center py-12"> <div className="mx-auto grid w-[350px] gap-6"> <div className="grid gap-2 text-center"> <h1 className="text-3xl font-bold">Sign In</h1> <p className="text-balance text-muted-foreground">Enter your email below to sign in to your account</p> </div> {providers .filter((provider) => (typeof provider === 'function' ? provider({}).id : provider.id) !== 'credentials') .map((provider) => ( <Provider prefix="Sign in" key={typeof provider === 'function' ? provider({}).name : provider.name} provider={typeof provider === 'function' ? provider({}) : provider} /> ))} <p className="text-gray-300 text-xs text-center">OR</p> <form method="POST" className="grid gap-4" action="/api/auth/callback/credentials?kind=in"> <div className="grid gap-2"> <Label htmlFor="email">Email</Label> <Input name="email" id="email" type="email" placeholder="m@example.com" required /> </div> <div className="grid gap-2"> <Label htmlFor="password">Password</Label> <Input name="password" id="password" type="password" required /> <CSRFInput /> </div> <Button type="submit" className="w-full"> Sign In </Button> </form> <div className="mt-4 text-center text-sm"> Don&apos;t have an account?{' '} <Link href="/signup" className="underline"> Sign up </Link> </div> </div> </div> ) }

Trong mã trên, một trang đăng nhập đang được tạo. Nó kiểm tra xem session người dùng đã tồn tại chưa; nếu có, nó chuyển hướng đến trang chủ. Trang hiển thị form đăng nhập nơi người dùng có thể nhập email và mật khẩu, cùng với các tùy chọn đăng nhập bằng các nhà cung cấp khác nhau. Nó cũng bao gồm token CSRF cho bảo mật và liên kết đến trang đăng ký cho người dùng mới.

Xây Dựng Trang Đăng Ký Động (Sử Dụng Auth.js)

Tạo tệp tên page.tsx trong thư mục app/signup với mã sau:

// File: app/signup/page.tsx export const runtime = 'edge' import { CSRFInput } from '@/app/csrf' import Provider from '@/app/provider' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { auth } from '@/lib/auth' import providers from '@/lib/providers' import { unstable_noStore } from 'next/cache' import Link from 'next/link' import { redirect } from 'next/navigation' export default async function () { unstable_noStore() const session = await auth() if (session) redirect('/') return ( <div className="border md:border-white/10 flex items-center justify-center py-12"> <div className="mx-auto grid w-[350px] gap-6"> <div className="grid gap-2 text-center"> <h1 className="text-3xl font-bold">Sign Up</h1> <p className="text-balance text-muted-foreground">Enter your email below to sign up with an account</p> </div> {providers .filter((provider) => (typeof provider === 'function' ? provider({}).id : provider.id) !== 'credentials') .map((provider) => ( <Provider prefix="Sign up" key={typeof provider === 'function' ? provider({}).name : provider.name} provider={typeof provider === 'function' ? provider({}) : provider} /> ))} <p className="text-gray-300 text-xs text-center">OR</p> <form method="POST" className="grid gap-4" action="/api/auth/callback/credentials?kind=up"> <div className="grid gap-2"> <Label htmlFor="email">Email</Label> <Input name="email" id="email" type="email" placeholder="m@example.com" required /> </div> <div className="grid gap-2"> <div className="flex items-center"> <Label htmlFor="password">Password</Label> </div> <Input name="password" id="password" type="password" required /> <CSRFInput /> </div> <Button type="submit" className="w-full"> Sign Up </Button> </form> <div className="mt-4 text-center text-sm"> Don&apos;t have an account?{' '} <Link href="/signin" className="underline"> Sign In </Link> </div> </div> </div> ) }

Trong mã trên, một trang đăng ký đang được tạo. Nó kiểm tra xem session người dùng đã tồn tại chưa; nếu có, nó chuyển hướng đến trang chủ. Trang hiển thị form đăng ký nơi người dùng có thể nhập email và mật khẩu, cùng với các tùy chọn đăng nhập bằng các nhà cung cấp khác nhau. Nó cũng bao gồm token CSRF cho bảo mật và liên kết đến trang đăng nhập cho người dùng hiện có.

Đó là rất nhiều kiến thức! Bây giờ bạn đã xong ✨

Tham Khảo

Để có thêm chi tiết, hãy khám phá các tham khảo được trích dẫn trong bài blog này.

  • GitHub Repository
  • Auth.js - Credentials Authentication
  • Auth.js - Upstash Redis Adapter
  • Next.js - Cookies

Kết Luận

Trong hướng dẫn này, bạn đã học cách triển khai xác thực người dùng trong ứng dụng Next.js sử dụng Auth.js và Upstash Redis. Bạn đã học thiết lập biến môi trường, tạo client Redis, và triển khai nhà cung cấp xác thực tùy chỉnh. Ngoài ra, bạn đã học cách thiết lập API routes trong Next.js để xử lý quy trình đăng nhập và đăng ký của người dùng, cũng như quản lý session. Bằng cách làm theo các bước này, bạn có thể quản lý hiệu quả xác thực người dùng và lưu trữ dữ liệu trong ứng dụng Next.js của mình với Upstash Redis.