Our app integrates magic link authentication using the Auth.js library. This method allows users to log in securely by receiving a magic link in their email.
Let's explore how to implement and use the magic link authentication in our app.
Ensure that the sendGridLogin setting is enabled in your settings.js file to use SendGrid for sending magic links. This setting should be set to true.
1 // In settings.js2 const config = {3 ...4 appInfo: {5 ...6 sendGridLogin: true, // Ensure this is true7 ...8 },9 ...10 };Before implementing Magic Link authentication, ensure that the NEXTAUTH_URL and NEXTAUTH_SECRET environment variables are set up in your .env.local file.
1 // .env.local2 NEXTAUTH_URL='http://localhost:3000'3 NEXTAUTH_SECRET='YOUR_RANDOMLY_GENERATED_SECRET'The NEXTAUTH_SECRET is a random encrypted key. You can generate any random string for development purposes. This key is crucial for securing sessions and encrypting tokens in your Next.js application.
1 import { signIn } from 'next-auth/react';2 3 const LoginPage = () => {4 const handleLogin = async (email) => {5 await signIn('email', { email });6 alert('Check your email for the magic link!');7 };8 return (9 <div>10 <h1>Login with Magic Link</h1>11 <input type='email' placeholder='Enter your email' onChange={(e) => setEmail(e.target.value)} />12 <button onClick={() => handleLogin(email)}>Send Magic Link</button>13 </div>14 );15 };