paint-brush
NextAuth.js, Shadcn/ui, react-hook-form, এবং Zod-এর সাহায্যে Next.js 14-এ কীভাবে প্রমাণীকরণ প্রয়োগ করা যায়দ্বারা@ljaviertovar
1,376 পড়া
1,376 পড়া

NextAuth.js, Shadcn/ui, react-hook-form, এবং Zod-এর সাহায্যে Next.js 14-এ কীভাবে প্রমাণীকরণ প্রয়োগ করা যায়

দ্বারা L Javier Tovar19m2024/03/01
Read on Terminal Reader

অতিদীর্ঘ; পড়তে

জাভাস্ক্রিপ্ট ইকোসিস্টেমের মধ্যে এবং আরও নির্দিষ্টভাবে, Next.js-এর সাহায্যে তৈরি করা অ্যাপ্লিকেশনগুলিতে, প্রমাণীকরণ পরিচালনার জন্য সবচেয়ে বিশিষ্ট লাইব্রেরিগুলির মধ্যে একটি হল NextAuth.js। এই টুলটি আমাদের অ্যাপ্লিকেশানগুলিতে প্রমাণীকরণ যোগ করার জন্য একটি সহজ এবং সহজে কার্যকরী সমাধান প্রদান করে। সবচেয়ে ভালো জিনিস হল এর নমনীয়তা; এটি ক্লাসিক ইমেল এবং পাসওয়ার্ডের মতো শংসাপত্র-ভিত্তিক প্রমাণীকরণ ছাড়াও Google, Facebook এবং Twitter এর মতো বিভিন্ন প্রমাণীকরণ প্রদানকারীর একীকরণের অনুমতি দেয়।
featured image - NextAuth.js, Shadcn/ui, react-hook-form, এবং Zod-এর সাহায্যে Next.js 14-এ কীভাবে প্রমাণীকরণ প্রয়োগ করা যায়
L Javier Tovar HackerNoon profile picture
0-item
1-item

একটি ব্যাপক নির্দেশিকা: শংসাপত্র (ইমেল এবং পাসওয়ার্ড)

ব্যবহারকারীদের নিরাপত্তা এবং গোপনীয়তা নিশ্চিত করা আগের চেয়ে অনেক বেশি গুরুত্বপূর্ণ। ওয়েব প্রমাণীকরণ এই দিকটিতে একটি গুরুত্বপূর্ণ ভূমিকা পালন করে, ব্যবহারকারীদের তথ্য এবং ডেটা সুরক্ষার জন্য প্রতিরক্ষার প্রথম লাইন হিসাবে পরিবেশন করে।


আজ, আমাদের কাছে NextAuth.js-এর মতো টুল রয়েছে যা আমাদের কাজকে আরও সহজ করে তোলে, যা আমাদের Next.js অ্যাপ্লিকেশনে বিভিন্ন ধরনের প্রমাণীকরণ সহজে বাস্তবায়ন করতে দেয়।


এই সিরিজের টিউটোরিয়ালগুলিতে, আমরা Next.js 14-এ একটি সম্পূর্ণ প্রমাণীকরণ সিস্টেম তৈরি করতে যাচ্ছি, যার মূল বিষয়গুলি: ইমেল এবং পাসওয়ার্ড দিয়ে প্রমাণীকরণ।

NextAuth.js (Auth.js) কি?

জাভাস্ক্রিপ্ট ইকোসিস্টেমের মধ্যে এবং আরও নির্দিষ্টভাবে, Next.js-এর সাহায্যে তৈরি করা অ্যাপ্লিকেশনগুলিতে, প্রমাণীকরণ পরিচালনার জন্য সবচেয়ে বিশিষ্ট লাইব্রেরিগুলির মধ্যে একটি হল NextAuth.js।


এই টুলটি আমাদের অ্যাপ্লিকেশানগুলিতে প্রমাণীকরণ যোগ করার জন্য একটি সহজ এবং সহজে কার্যকরী সমাধান প্রদান করে। সবচেয়ে ভালো জিনিস হল এর নমনীয়তা; এটি ক্লাসিক ইমেল এবং পাসওয়ার্ডের মতো শংসাপত্র-ভিত্তিক প্রমাণীকরণ ছাড়াও Google, Facebook এবং Twitter এর মতো বিভিন্ন প্রমাণীকরণ প্রদানকারীর একীকরণের অনুমতি দেয়।

শংসাপত্র প্রমাণীকরণ বাস্তবায়ন

শংসাপত্র প্রমাণীকরণ বিশেষত এমন অ্যাপ্লিকেশনগুলিতে উপযোগী যেখানে আপনার প্রমাণীকরণ প্রক্রিয়া এবং ব্যবহারকারীর শংসাপত্রের সঞ্চয়স্থানের উপর সম্পূর্ণ নিয়ন্ত্রণ প্রয়োজন, বা যখন আপনি বহিরাগত প্রমাণীকরণ প্রদানকারীদের উপর নির্ভর করতে চান না।

ঠিককরা

  1. নিম্নলিখিত কমান্ড সহ একটি নতুন Next.js প্রকল্প তৈরি করুন এবং নির্দেশিত পদক্ষেপগুলি অনুসরণ করুন। আমরা TypeScript এবং src/ ফোল্ডার ব্যবহার করব।


 npx create-next-app@latest


2. প্রকল্পে প্রয়োজনীয় নির্ভরতা ইনস্টল করুন। এইবার, আমরা pnpm ব্যবহার করব; আপনি আপনার পছন্দের প্যাকেজ ম্যানেজার ব্যবহার করতে পারেন।


 pnpm install next-auth prisma react-hook-form zod, bcrypt


UI এর জন্য, আমরা Shadcn/ui ব্যবহার করব।


 pnpm dlx shadcn-ui@latest init


  • প্রিজমা : একটি ওপেন সোর্স ডাটাবেস টুলকিট। আমরা ব্যবহারকারীর শংসাপত্র সংরক্ষণ করতে এটি ব্যবহার করব।

  • পরবর্তী-প্রমাণ : Next.js এর জন্য প্রমাণীকরণ।

  • প্রতিক্রিয়া-হুক-ফর্ম : একটি লাইব্রেরি যা আপনাকে প্রতিক্রিয়াতে ফর্মগুলি যাচাই করতে সহায়তা করে।

  • জোড : একটি তথ্য যাচাইকারী।

  • bcrypt : পাসওয়ার্ড হ্যাশ করতে।

  • shadcn/ui : পুনঃব্যবহারযোগ্য উপাদানের একটি সংগ্রহ।


3. প্রকল্পের জন্য নিম্নলিখিত কাঠামো তৈরি করুন:


 ... ├── prisma/ ... ├── src/ │ ├── actions/ │ │ └── auth-actions.tsx │ ├── app/ │ │ ├── api/auth/[...nextauth] │ │ │ └── route.ts │ │ ├── auth/ │ │ │ ├── signin │ │ │ │ └── page.tsx │ │ │ └── signup │ │ │ └── page.tsx │ │ │ ... │ ├── components/ │ │ ├── auth/ │ │ │ ├── auth-buttons.tsx │ │ │ ├── signin-form.tsx │ │ │ ├── signup-form.tsx │ │ │ └── user-nav.ts │ │ ├── ui/ │ │ │ ... │ │ ├── auth-provider.tsx │ │ ├── icons.tsx │ │ └── theme-provider.tsx │ ├── lib/ │ │ ├── prisma.ts │ │ ├── types.d.ts │ │ └── utils.ts │ ... ...


প্রিজমা সেট আপ করা হচ্ছে

আমরা ডাটাবেসে ব্যবহারকারীদের সংরক্ষণ এবং পুনরুদ্ধার করতে Prisma ব্যবহার করব। প্রিজমা বিভিন্ন ধরনের ডাটাবেস একীকরণের অনুমতি দেয় যাতে আপনি আপনার প্রয়োজনে যেকোনো ডাটাবেস ব্যবহার করতে পারেন, আমরা SQLite ব্যবহার করব।


  1. প্রিজমা শুরু করা হচ্ছে


 npx prisma init --datasource-provider sqlite


এটি তার স্কিমা সহ প্রিজম ফোল্ডার তৈরি করে।


  1. মডেল তৈরি করা।

মডেলগুলি তৈরি করতে, আমরা @auth/prisma-adapter দ্বারা প্রদত্ত যেগুলি ব্যবহার করব এবং সেগুলিকে নিম্নরূপ একটু কাস্টমাইজ করব:


prisma/schema.prisma :


 generator client { provider = "prisma-client-js" output = "../../node_modules/.prisma/client" } datasource db { provider = "sqlite" url = env("DATABASE_URL") } ... model User { id String @id @default(cuid()) username String password String email String @unique emailVerified DateTime? phone String? image String? } ...


3. প্রথম তৈরি করা মাইগ্রেশন .


 npx prisma migrate dev --name first-migration


এই কমান্ডের সাহায্যে, প্রিজমা ফোল্ডারে আরও ফাইল তৈরি করা হয়েছে, এবং ডেটাবেস মডেলগুলির সাথে সিঙ্ক্রোনাইজ করা হয়েছে।


4. প্রিজমা ক্লায়েন্ট

অবশেষে, আমরা একটি প্রিজমা ক্লায়েন্ট তৈরি করি।


lib/prisma.ts :


 import { PrismaClient } from "@prisma/client"; const globalForPrisma = global as unknown as { prisma: PrismaClient; }; export const prisma = globalForPrisma.prisma || new PrismaClient(); if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; export default prisma;


NextAuth.js সেট আপ করা হচ্ছে

  1. env ভেরিয়েবল তৈরি করা।


 # Secret key for NextAuth.js, used for encryption and session security. It should be a long, # random string unique to your application. NEXTAUTH_SECRET=XXX3B2CC28F123456C6934531CXXXXX # Base URL for your Next.js app, used by NextAuth.js for redirects and callbacks. NEXTAUTH_URL=http://localhost:3000/


  1. প্রমাণীকরণ রুট তৈরি করা হচ্ছে।

এই পথটি একটি একক এন্ডপয়েন্টে সমস্ত প্রমাণীকরণ অনুরোধ (যেমন লগইন, লগআউট এবং ভেন্ডর কলব্যাক) পরিচালনা করার অনুমতি দেয়।


src/app/api/auth/[...nextauth]


  1. প্রদানকারীদের তৈরি করা।


 ... // Imports the Prisma User type for typing. import { User } from '@prisma/client' // Configuration of authentication options for NextAuth. export const authOptions: AuthOptions = { ... // Defines authentication providers, in this case, only credentials. providers: [ CredentialsProvider({ name: 'Credentials', // Defines the required fields for authentication. credentials: { email: { label: 'Email', type: 'text' }, password: { label: 'Password', type: 'password' }, }, // Function to authenticate the user with the provided credentials. async authorize(credentials) { // Searches for the user in the database by email. const user = await prisma.user.findUnique({ where: { email: credentials?.email, }, }) // Checks if the user exists and if the password is correct. if (!user) throw new Error('User name or password is not correct') if (!credentials?.password) throw new Error('Please Provide Your Password') const isPasswordCorrect = await bcrypt.compare(credentials.password, user.password) if (!isPasswordCorrect) throw new Error('User name or password is not correct') // Returns the user without including the password. const { password, ...userWithoutPass } = user return userWithoutPass }, }), ], } // Exports the configured NextAuth handler to handle GET and POST requests. const handler = NextAuth(authOptions) export { handler as GET, handler as POST }


4. প্রমাণ প্রদানকারী তৈরি করা।


src/components/auth-provider.tsx :


 'use client' import { SessionProvider } from 'next-auth/react' export default function AuthProvider({ children }: { children: React.ReactNode }) { return <SessionProvider>{children}</SessionProvider> }


এই উপাদানটি Next.js অ্যাপ্লিকেশনগুলির জন্য একটি সেশন প্রদানকারী হিসাবে কাজ করে যা প্রমাণীকরণের জন্য NextAuth ব্যবহার করে।


এই প্রদানকারীর উপাদান বা পৃষ্ঠাগুলিকে মোড়ানো তাদের সেশন প্রসঙ্গে অ্যাক্সেস মঞ্জুর করে, যা চাইল্ড উপাদানগুলিকে NextAuth হুক এবং কার্যকারিতা ব্যবহার করার অনুমতি দেয়, যেমন useSession , ব্যবহারকারীর বর্তমান সেশনের অবস্থা অ্যাক্সেস বা পরিবর্তন করতে।


src/app/layout.tsx :


 /* All imports */ export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang='en' suppressHydrationWarning > <body className={`${inter.className} relative`}> <AuthProvider> <main>{children}</main> </AuthProvider> </body> </html> ) }


Shadcn/ui দিয়ে UI সেট আপ করা হচ্ছে

  1. অনুসরণ করে shadcn/ui ইনস্টল করা হচ্ছে ডকুমেন্টেশন (ধাপ 2) .


 Would you like to use TypeScript (recommended)? yes Which style would you like to use? › Default Which color would you like to use as base color? › Slate Where is your global CSS file? › src/app/globals.css Do you want to use CSS variables for colors? › yes Are you using a custom tailwind prefix eg. tw-? Leave blank Where is your tailwind.config.js located? › tailwind.config.js Configure the import alias for components: › @/components Configure the import alias for utils: › @/lib/utils Are you using React Server Components? › yes


আপনি আপনার পছন্দের থিম ব্যবহার করতে পারেন।


2. বাস্তবায়ন করা ডার্ক মোড


src/app/layout.tsx :


 /* All imports */ export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang='en' suppressHydrationWarning > <body className={`${inter.className} relative`}> <AuthProvider> <ThemeProvider attribute='class' defaultTheme='dark' enableSystem disableTransitionOnChange > <main>{children}</main> <Toaster /> </ThemeProvider> </AuthProvider> </body> </html> ) }


2. নিম্নলিখিত shadcn/ui উপাদানগুলি ইনস্টল করা হচ্ছে:


 pnpm dlx shadcn-ui@latest add avatar button dropdown-menu form input label tabs toast


প্রমাণীকরণ উপাদান তৈরি করা

src/components/auth-buttons.tsx :


 'use client' import Link from 'next/link' import { signIn, useSession } from 'next-auth/react' import { Button } from '../ui/button' import { UserNav } from './user-nav' export default function AuthButtons() { // Use the useSession hook to access session data const { data: session } = useSession() return ( <div className='flex justify-end gap-4'> {session && session.user ? ( <UserNav user={session.user} /> ) : ( <> <Button size={'sm'} variant={'secondary'} onClick={() => signIn()} > Sign In </Button> <Button size={'sm'} asChild className='text-foreground' > <Link href='/auth/signup'>Sign Up</Link> </Button> </> )} </div> ) }


এই উপাদানটি ব্যবহারকারীর সেশনের অবস্থার উপর ভিত্তি করে গতিশীলভাবে প্রমাণীকরণ বিকল্পগুলি প্রদর্শন করে। ব্যবহারকারী লগ ইন করা থাকলে, এটি ব্যবহারকারী-নির্দিষ্ট নেভিগেশন দেখায়। অন্যথায়, এটি একটি মসৃণ ব্যবহারকারীর অভিজ্ঞতার জন্য Next.js এর রাউটিং এবং NextAuth-এর প্রমাণীকরণ ক্ষমতা ব্যবহার করে সাইন ইন বা সাইন আপ করার জন্য বোতাম অফার করে।


হোম পেজ পরিবর্তন করুন, এবং প্রমাণীকরণ বোতাম যোগ করুন। এই এটা দেখায় কিভাবে হয়:


হোম পেজ

src/components/auth/signup-form.tsx :


 'use client' /* all imports */ // Function to register a new user import { registerUser } from '@/actions/auth-actions' // Define the validation schema for the signup form using Zod const formSchema = z .object({ username: z .string({ required_error: 'Username is required', }) .min(2, 'User name must have at least 2 characters') .max(12, 'Username must be up to 12 characters') .regex(new RegExp('^[a-zA-Z0-9]+$'), 'No special characters allowed!'), email: z.string({ required_error: 'Email is required' }).email('Please enter a valid email address'), password: z .string({ required_error: 'Password is required' }) .min(6, 'Password must have at least 6 characters') .max(20, 'Password must be up to 20 characters'), confirmPassword: z .string({ required_error: 'Confirm your password is required' }) .min(6, 'Password must have at least 6 characters') .max(20, 'Password must be up to 20 characters'), }) .refine(values => values.password === values.confirmPassword, { message: "Password and Confirm Password doesn't match!", path: ['confirmPassword'], }) // Type inference for form inputs based on the Zod schema type InputType = z.infer<typeof formSchema> export function SignUpForm() { const [isLoading, setIsLoading] = useState(false) const { toast } = useToast() // Hook to show toast notifications // Initialize form handling with React Hook Form and Zod for validation const form = useForm<InputType>({ resolver: zodResolver(formSchema), }) // Handles form submission async function onSubmit(values: InputType) { try { setIsLoading(true) const { confirmPassword, ...user } = values // Exclude confirmPassword from data to be sent const response = await registerUser(user) // Register the user if ('error' in response) { toast({ title: 'Something went wrong!', description: response.error, variant: 'success', }) } else { toast({ title: 'Account Created!', description: 'Your account has been created successfully! You can now login.', }) } } catch (error) { console.error(error) toast({ title: 'Something went wrong!', description: "We couldn't create your account. Please try again later!", variant: 'destructive', }) } finally { setIsLoading(false) } } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}> <div className='grid gap-2'> // Each FormField validates and displays an input <FormField control={form.control} name='username' render={({ field }) => ( <FormItem> <FormControl> <div className='flex items-center gap-2'> <Icons.user className={`${form.formState.errors.username ? 'text-destructive' : 'text-muted-foreground'} `} /> <Input placeholder='Your Username' className={`${form.formState.errors.username && 'border-destructive bg-destructive/30'}`} {...field} /> </div> </FormControl> <FormMessage /> </FormItem> )} /> // Repeated structure for email, password, and confirmPassword with respective validations and icons <Button className='text-foreground mt-4' disabled={isLoading} // Disable button during form submission > {isLoading && <Icons.spinner className='mr-2 h-4 w-4 animate-spin' />} // Show loading icon if isLoading is true Sign Up </Button> </div> </form> </Form> ) }


এই উপাদানটি একটি ইউজার রেজিস্ট্রেশন ফর্মকে এনক্যাপসুলেট করে, ফর্ম স্টেট ম্যানেজমেন্টের জন্য রিঅ্যাক্ট-হুক-ফর্ম এবং স্কিমা বৈধতার জন্য Zod ব্যবহার করে।


যদিও এটি এই প্রযুক্তিগুলির উপর একটি টিউটোরিয়াল নয়, আমরা শুধুমাত্র সেগুলির মৌলিক বিষয়গুলি ব্যবহার করছি, যদি আপনার আরও প্রশ্ন থাকে, আপনি তাদের ডকুমেন্টেশনে যেতে পারেন৷


আমি পৃষ্ঠায় আরও কিছু শৈলী যোগ করেছি এবং এটি এইরকম দেখাচ্ছে:


সাইন আপ পৃষ্ঠা



src/actions/auth-action/ts :


 'use server' /* all imports */ export async function registerUser(user: Omit<User, 'id' | 'phone' | 'emailVerified' | 'image'>) { try { // Attempt to create a new user record in the database const result = await prisma.user.create({ data: { ...user, // Hash the password before storing it password: await bcrypt.hash(user.password, 10), }, }) return result } catch (error) { console.log(error) // Handle known request errors from Prisma if (error instanceof Prisma.PrismaClientKnownRequestError) { // Check for unique constraint failure (eg, email already exists) if (error.code === 'P2002') { return { error: 'Email already exists.' } } } // Return a generic error message for any other errors return { error: 'An unexpected error occurred.' } } }


registerUser ফাংশনটি id , phone , emailVerified , এবং image মত ক্ষেত্রগুলি বাদ দিয়ে প্রদত্ত ব্যবহারকারীর তথ্য সহ ডাটাবেসে একটি রেকর্ড তৈরি করে নিরাপদে একজন নতুন ব্যবহারকারীকে নিবন্ধন করার জন্য ডিজাইন করা হয়েছে৷


এটি নিরাপদ স্টোরেজের জন্য ব্যবহারকারীর পাসওয়ার্ড হ্যাশ করতে bcrypt ব্যবহার করে।


আমাদের সাইন-আপ পরীক্ষা করতে এবং ব্যবহারকারী সঠিকভাবে নিবন্ধন করছেন তা যাচাই করতে, আমাদের কিছু কলব্যাক যোগ করতে হবে; এগুলি এমন ফাংশন যা আপনাকে প্রমাণীকরণ এবং সেশন পরিচালনার আচরণ কাস্টমাইজ করতে দেয়।


src/app/api/auth/[...nextauth] :


 ... export const authOptions: AuthOptions = { // Define custom pages for authentication flow pages: { signIn: '/auth/signin', // Custom sign-in page }, // Configure session management to use JSON Web Tokens (JWT) session: { strategy: 'jwt', }, // JWT configuration, including secret for token signing jwt: { secret: process.env.NEXTAUTH_SECRET, // Secret used to sign the JWT, stored in environment variables }, ... // Callbacks for customizing JWT and session behaviors callbacks: { // Callback to modify the JWT content. Adds user information if available. async jwt({ token, user }) { if (user) token.user = user as User // Cast user object to User type and assign to token return token }, // Callback to modify session content. Adds user information to the session. async session({ token, session }) { session.user = token.user // Assign user information from token to session return session }, }, } ...


কলব্যাক jwt : যখনই একটি JSON ওয়েব টোকেন (JWT) তৈরি করা হয় বা প্রমাণীকরণের জীবনচক্রের সময় আপডেট করা হয় তখন এই কলব্যাকটি কার্যকর করা হয়। এটি আপনাকে টোকেনের বিষয়বস্তু পরিবর্তন করার অনুমতি দেয় এটি স্বাক্ষরিত হওয়ার আগে এবং ক্লায়েন্টের কাছে পাঠানো বা সার্ভারে সংরক্ষণ করা হয়।


এটি টোকেনে অতিরিক্ত তথ্য যোগ করার জন্য উপযোগী, যা আপনার আবেদনের যুক্তির সাথে প্রাসঙ্গিক হতে পারে।


কলব্যাক session : এই কলব্যাকটি প্রতিবার সেশনের ডেটা পড়ার সময় বলা হয়, যেমন সার্ভার-সাইড রেন্ডারিংয়ের সময় বা সুরক্ষিত API অনুরোধগুলিতে। এটি ক্লায়েন্টের কাছে পাঠানোর আগে সেশন ডেটা পরিবর্তন করার অনুমতি দেয়।


এটি JWT বা অন্যান্য মানদণ্ডে সংরক্ষিত তথ্যের উপর ভিত্তি করে সেশন ডেটা যোগ বা পরিবর্তন করার জন্য বিশেষভাবে কার্যকর।


অবশেষে, অতিরিক্ত ব্যবহারকারীর তথ্য অন্তর্ভুক্ত করার জন্য আমাদের NextAuth Session এবং JWT প্রকারের সংজ্ঞা প্রসারিত করতে হবে।


src/lib/types.d.ts :


 import { User } from '@prisma/client' declare module 'next-auth' { interface Session { user: User } } declare module 'next-auth/jwt' { interface JWT { user: User } }


এখন, আমরা যদি ফর্মটি পূরণ করে জমা দিই, তাহলে আমরা সাফল্যের টোস্ট দেখতে সক্ষম হব। ব্যবহারকারী ডাটাবেসে সংরক্ষিত হয়েছে তা যাচাই করার জন্য, আমরা নিম্নলিখিত কমান্ডের সাহায্যে প্রিজমা দ্বারা তৈরি টেবিলগুলি গ্রাফিকভাবে দেখতে পারি:


 nxp prisma studio


আমরা নিম্নলিখিত রুট http://localhost:5555 উপলব্ধ করব


প্রিজমা স্টুডিও


src/components/auth/user-nav.tsx :


 /* all imports */ interface Props { user: User // Expect a user object of type User from Prisma client } export function UserNav({ user }: Props) { return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant='ghost' className='relative h-8 w-8 rounded-full' > <Avatar className='h-9 w-9'> <AvatarImage src='/img/avatars/01.png' alt='' /> <AvatarFallback>UU</AvatarFallback> </Avatar> </Button> </DropdownMenuTrigger> <DropdownMenuContent className='w-56' align='end' forceMount > <DropdownMenuLabel className='font-normal'> <div className='flex flex-col space-y-1'> <p className='text-sm font-medium leading-none'>{user.username}</p> <p className='text-xs leading-none text-muted-foreground'>{user.email}</p> </div> </DropdownMenuLabel> <DropdownMenuSeparator /> <DropdownMenuItem> <Link href={'/api/auth/signout'} // Link to the signout API route className='w-full' > Sign Out </Link> </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) } 


হোম পেজ



src/components/auth/signin-form.tsx :


 /* all imports */ // Schema definition for form validation using Zod const formSchema = z.object({ email: z.string({ required_error: 'Please enter your email' }).email('Please enter a valid email address'), password: z.string({ required_error: 'Please enter your password', }), }) // Type inference for form inputs based on the Zod schema type InputType = z.infer<typeof formSchema> // Props definition, optionally including a callback URL interface Props { callbackUrl?: string } export function SignInForm({ callbackUrl }: Props) { const [isLoading, setIsLoading] = useState(false) const { toast } = useToast() const router = useRouter() // Hook to control routing const form = useForm<InputType>({ resolver: zodResolver(formSchema), // Set up Zod as the form validation resolver }) // Function to handle form submission async function onSubmit(values: InputType) { try { setIsLoading(true) // Attempt to sign in using the 'credentials' provider const response = await signIn('credentials', { redirect: false, // Prevent automatic redirection email: values.email, password: values.password, }) // Handle unsuccessful sign in attempts if (!response?.ok) { toast({ title: 'Something went wrong!', description: response?.error, variant: 'destructive', }) return } toast({ title: 'Welcome back! ', description: 'Redirecting you to your dashboard!', }) router.push(callbackUrl ? callbackUrl : '/') // Redirect to the callback URL or home page } catch (error) { toast({ title: 'Something went wrong!', description: "We couldn't create your account. Please try again later!", variant: 'destructive', }) } finally { setIsLoading(false) } } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}> <div className='grid gap-2'> <div className='grid gap-1'> <FormField control={form.control} name='email' render={({ field }) => ( <FormItem> <FormControl> <div className='flex items-center gap-2'> <Icons.email className={`${form.formState.errors.email ? 'text-destructive' : 'text-muted-foreground'} `}/> <Input type='email' placeholder='Your Email' className={`${form.formState.errors.email && 'border-destructive bg-destructive/30'}`} {...field} /> </div> </FormControl> <FormMessage /> </FormItem> )} /> {/* Password field */} {/* Similar structure to email field, customized for password input */} </div> <Button className='text-foreground mt-4' disabled={isLoading} // Disable button while loading > {isLoading && <Icons.spinner className='mr-2 h-4 w-4 animate-spin' />} // Show loading spinner when processing Sign In </Button> </div> </form> </Form> ) } 


সাইন ইন পৃষ্ঠা


🎉 হয়ে গেছে!


আমরা NextAuth.js এর সাথে একটি মৌলিক প্রমাণীকরণ বাস্তবায়ন শেষ করেছি। একটি সম্পূর্ণ প্রমাণীকরণ সিস্টেম পেতে এখনও অনেক কিছু করতে হবে এবং আমরা পরবর্তী টিউটোরিয়ালগুলিতে সেগুলি কভার করব।


🔗 এখানে রেপো


উপসংহার

সংক্ষেপে, আমরা নেক্সটআউথ ব্যবহার করে Next.js-এ একটি প্রমাণীকরণ সিস্টেম কীভাবে বাস্তবায়ন এবং কাস্টমাইজ করা যায়, ব্যবহারকারী ব্যবস্থাপনাকে সমৃদ্ধ করার জন্য কীভাবে সেশন এবং JWTs প্রসারিত করা যায় এবং কীভাবে প্রতিক্রিয়া-হুক-ফর্ম এবং Zod ব্যবহার করে কার্যকরী বৈধতা সহ ফর্মগুলি পরিচালনা করা যায় তা অনুসন্ধান করেছি।


লেখকের সাথে সংযোগ করতে চান?


সারা বিশ্বের বন্ধুদের সাথে সংযোগ করতে ভালোবাসি 𝕏 .


এছাড়াও এখানে প্রকাশিত