Passwordless authentication with email magic links.
Note: This is mock/placeholder content for demonstration purposes.
Magic links provide passwordless authentication by sending a one-time link to the user's email.
How It Works
User enters their email address
System sends an email with a unique link
User clicks the link in their email
User is automatically signed in
Benefits
No password to remember - Better UX
More secure - No password to steal
Lower friction - Faster sign-up process
Email verification - Confirms email ownership
Implementation
Magic Link Form
'use client';
import { useForm } from 'react-hook-form';
import { sendMagicLinkAction } from '../_lib/actions';
export function MagicLinkForm() {
const { register, handleSubmit, formState: { isSubmitting } } = useForm();
const [sent, setSent] = useState(false);
const onSubmit = async (data) => {
const result = await sendMagicLinkAction(data);
if (result.success) {
setSent(true);
}
};
if (sent) {
return (
<div className="text-center">
<h2>Check your email</h2>
<p>We've sent you a magic link to sign in.</p>
</div>
);
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>Email address</label>
<input
type="email"
{...register('email', { required: true })}
placeholder="[email protected]"
/>
</div>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Sending...' : 'Send magic link'}
</button>
</form>
);
}
Server Action
'use server';
import { enhanceAction } from '@kit/next/actions';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { z } from 'zod';
export const sendMagicLinkAction = enhanceAction(
async (data) => {
const client = getSupabaseServerClient();
const origin = process.env.NEXT_PUBLIC_SITE_URL!;
const { error } = await client.auth.signInWithOtp({
email: data.email,
options: {
emailRedirectTo: `${origin}/auth/callback`,
shouldCreateUser: true,
},
});
if (error) throw error;
return {
success: true,
message: 'Check your email for the magic link',
};
},
{
schema: z.object({
email: z.string().email(),
}),
}
);
Configuration
Enable in Supabase
Go to Authentication → Providers → Email
Enable "Enable Email Provider"
Enable "Enable Email Confirmations"
Configure Email Template
Customize the magic link email in Supabase Dashboard:
Go to Authentication → Email Templates
Select "Magic Link"
Customize the template:
<h2>Sign in to {{ .SiteURL }}</h2>
<p>Click the link below to sign in:</p>
<p><a href="{{ .ConfirmationURL }}">Sign in</a></p>
<p>This link expires in {{ .TokenExpiryHours }} hours.</p>
Callback Handler
Handle the magic link callback:
// app/auth/callback/route.ts
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
const requestUrl = new URL(request.url);
const token_hash = requestUrl.searchParams.get('token_hash');
const type = requestUrl.searchParams.get('type');
if (token_hash && type === 'magiclink') {
const cookieStore = cookies();
const supabase = createRouteHandlerClient({ cookies: () => cookieStore });
const { error } = await supabase.auth.verifyOtp({
token_hash,
type: 'magiclink',
});
if (!error) {
return NextResponse.redirect(new URL('/home', request.url));
}
}
// Return error if verification failed
return NextResponse.redirect(
new URL('/auth/sign-in?error=invalid_link', request.url)
);
}
// Handle email bounces
export async function handleEmailBounce(email: string) {
await client.from('email_bounces').insert({
email,
bounced_at: new Date(),
});
// Notify user via other channel
}
Testing
Local Development
In development, emails go to InBucket:
http://localhost:54324
Check this URL to see magic link emails during testing.
Test Mode
Create a test link without sending email:
if (process.env.NODE_ENV === 'development') {
console.log('Magic link URL:', confirmationUrl);
}