Prompt
How to send magic link and OTP emails
Latest observation
You said:
How to send magic link and OTP emails
ChatGPT said:
If you're building authentication for an app, magic link and OTP emails are usually handled through your authentication provider. If you're building your own auth system, you can send them through an email API such as Notify, Resend, or Postmark.
There are two common approaches.
- Magic link email
The user enters their email address and receives a link such as:
Sign in to Acme
To: user@example.com
Hi there,
Click the button below to securely sign in to your account.
Sign in to Acme
This link expires in 15 minutes. If you didn't request it, you can safely ignore this email.
The flow is:
-
Generate a cryptographically secure, single-use token.
-
Store a hash of the token alongside the user and its expiration time.
-
Email a link containing the token.
-
When the user clicks the link, validate the token, expire it, and create their authenticated session.
-
OTP email
Instead of a link, the user receives a short numeric code.
Your verification code
To: user@example.com
Use this code to sign in to your account.
482 916
This code expires in 10 minutes. Don't share it with anyone.
The flow is similar, except the user enters the code in your app. Your backend verifies it, checks the expiration and attempt limits, invalidates the code, and establishes a session.
How to implement this
For a typical application, you'll need three things:
- Authentication backend: Generates and validates tokens or codes, manages users, and creates sessions.
- Email delivery service: Sends the transactional email reliably.
- Email templates: HTML and plain-text versions of the magic link and OTP messages.
If you're using Supabase Auth, for example, it already supports magic links and email OTPs. You can configure custom email templates and connect your own SMTP provider. You don't need to build the token-generation and validation logic yourself.
If you're building your own authentication system, the email API only needs to send the message. Your application should retain responsibility for generating, validating, expiring, and consuming the authentication tokens.
One important detail: authentication emails should be fast and reliable, with appropriate SPF, DKIM, and DMARC configuration. Rate-limit requests and verification attempts, and avoid revealing whether an email address is registered.
What are you using to implement authentication? Supabase Auth, your own auth system, or something else? I can give you the exact implementation and email templates for your setup.