paint-brush
NextAuth.js, Shadcn/ui, प्रतिक्रिया-हुक-फॉर्म और ज़ोड के साथ Next.js 14 में प्रमाणीकरण कैसे लागू करेंद्वारा@ljaviertovar
1,376 रीडिंग
1,376 रीडिंग

NextAuth.js, Shadcn/ui, प्रतिक्रिया-हुक-फॉर्म और ज़ोड के साथ 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, प्रतिक्रिया-हुक-फॉर्म और ज़ोड के साथ 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 प्रोजेक्ट बनाएं और बताए गए चरणों का पालन करें। हम टाइपस्क्रिप्ट और src/ फ़ोल्डर का उपयोग करेंगे।


 npx create-next-app@latest


2. प्रोजेक्ट में आवश्यक निर्भरताएँ स्थापित करें। इस बार, हम pnpm उपयोग करेंगे; आप अपनी पसंद के पैकेज मैनेजर का उपयोग कर सकते हैं।


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


यूआई के लिए, हम 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 │ ... ...


प्रिज्मा की स्थापना

हम डेटाबेस में उपयोगकर्ताओं को संग्रहीत और पुनः प्राप्त करने के लिए प्रिज्मा का उपयोग करेंगे। प्रिज्मा विभिन्न डेटाबेस प्रकारों के एकीकरण की अनुमति देता है ताकि आप अपनी ज़रूरत के किसी भी डेटाबेस का उपयोग कर सकें, हम 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 का उपयोग करता है।


इस प्रदाता में घटकों या पृष्ठों को लपेटने से उन्हें सत्र संदर्भ तक पहुंच मिलती है, जिससे बाल घटकों को उपयोगकर्ता के वर्तमान सत्र की स्थिति तक पहुंचने या संशोधित करने के लिए नेक्स्टऑथ हुक और 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 के साथ यूआई की स्थापना

  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> ) }


यह घटक उपयोगकर्ता की सत्र स्थिति के आधार पर गतिशील रूप से प्रमाणीकरण विकल्प प्रदर्शित करता है। यदि उपयोगकर्ता लॉग इन है, तो यह उपयोगकर्ता-विशिष्ट नेविगेशन दिखाता है। अन्यथा, यह सहज उपयोगकर्ता अनुभव के लिए नेक्स्ट.जेएस की रूटिंग और नेक्स्टऑथ की प्रमाणीकरण क्षमताओं का उपयोग करते हुए साइन इन या साइन अप करने के लिए बटन प्रदान करता है।


होम पेज को संशोधित करें, और ऑथ बटन जोड़ें। यह इस प्रकार दिखता है:


होम पेज

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> ) }


यह घटक फॉर्म राज्य प्रबंधन के लिए रिएक्ट-हुक-फॉर्म और स्कीमा सत्यापन के लिए ज़ोड का उपयोग करते हुए एक उपयोगकर्ता पंजीकरण फॉर्म को समाहित करता है।


हालाँकि यह इन प्रौद्योगिकियों पर एक ट्यूटोरियल नहीं है, हम केवल उनकी मूल बातें का उपयोग कर रहे हैं, यदि आपके पास अधिक प्रश्न हैं, तो आप उनके दस्तावेज़ीकरण पर जा सकते हैं।


मैंने पेज पर कुछ और शैलियाँ जोड़ी हैं, और यह इस तरह दिखता है:


साइन अप पेज



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 : यह कॉलबैक हर बार सत्र डेटा पढ़ने पर कॉल किया जाता है, जैसे सर्वर-साइड रेंडरिंग के दौरान या संरक्षित एपीआई अनुरोधों में। यह क्लाइंट को भेजे जाने से पहले सत्र डेटा को संशोधित करने की अनुमति देता है।


यह जेडब्ल्यूटी या अन्य मानदंडों में संग्रहीत जानकारी के आधार पर सत्र डेटा जोड़ने या संशोधित करने के लिए विशेष रूप से उपयोगी है।


अंत में, हमें अतिरिक्त उपयोगकर्ता जानकारी शामिल करने के लिए 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 के साथ बुनियादी प्रमाणीकरण लागू करना पूरा कर लिया है। संपूर्ण प्रमाणीकरण प्रणाली बनाने के लिए अभी भी कई चीज़ें करनी बाकी हैं, और हम उन्हें अगले ट्यूटोरियल में शामिल करेंगे।


🔗 यहाँ रेपो


निष्कर्ष

संक्षेप में, हमने पता लगाया है कि नेक्स्टऑथ का उपयोग करके नेक्स्ट.जेएस में प्रमाणीकरण प्रणाली को कैसे कार्यान्वित और अनुकूलित किया जाए, उपयोगकर्ता प्रबंधन को समृद्ध करने के लिए सत्र और जेडब्ल्यूटी का विस्तार कैसे किया जाए, और रिएक्ट-हुक-फॉर्म और ज़ॉड का उपयोग करके प्रभावी सत्यापन के साथ फॉर्म को कैसे संभाला जाए।


लेखक से जुड़ना चाहते हैं?


दुनिया भर के दोस्तों के साथ जुड़ना पसंद है 𝕏 .


यहाँ भी प्रकाशित किया गया