Skip to content
send.io
All posts

Magic link authentication: how it works and implementation guide

Magic link authentication replaces passwords with single use tokens delivered by email. Learn how it works and implementation best practices. This guide covers token generation, database schema, validation logic, replay prevention, and delivery infrastructure for production systems.

On this page
TL;DR: Magic link authentication replaces passwords with a single-use token delivered by email. Generate tokens with at least 128 bits of entropy, set expiration to 10 to 15 minutes, and invalidate them immediately after first use. The security model depends on three code-level properties: unpredictable tokens, short TTL, and single-use enforcement. It also depends on one infrastructure property code can't control: the email must arrive before the user abandons the login attempt. This guide covers token generation (HMAC-SHA256 vs UUID), database schema, validation logic, replay prevention, and the delivery infrastructure that makes passwordless email login reliable in production.

Magic links don't eliminate the password problem. They move it from your database to your email delivery infrastructure, and implementation guides often skip the delivery infrastructure side entirely.

Magic link authentication replaces password verification with a single-use token delivered by email. The security model depends on three properties: the token is unpredictable, it expires quickly, and it can only be used once. Each of those properties is enforced in code, but the user experience depends on a fourth property that code can't control: the email actually arrives before the user gives up. This guide covers the token lifecycle end to end, from database schema to delivery infrastructure, with the specific failure modes that production systems hit.

Anatomy of a magic link auth flow

The magic link flow involves four actors: the client (browser or mobile app), your backend, the email provider, and the user. Here's the sequence:

  1. User enters their email address on your login page.
  2. Backend generates a cryptographically random token, stores it (or its hash) in the database, and triggers an email send.
  3. Email provider delivers the message containing the magic link URL.
  4. User clicks the link, which hits your validation endpoint.
  5. Backend validates the token (exists, not expired, not used), marks it as used, and establishes a session.

sequenceDiagram
participant U as User
participant C as Client
participant B as Backend
participant E as Email Provider

U->>C: Enter email
C->>B: POST /auth/magic-link
B->>B: Generate token (128-bit entropy)
B->>B: Store token_hash, expires_at
B->>E: Send email with link
E->>U: Deliver email
U->>C: Click magic link
C->>B: GET /auth/verify?token=xyz
B->>B: Validate token (exists, not expired, not used)
B->>B: Mark token as used (atomic update)
B->>C: Return session token
C->>U: Logged in

Each step is a potential failure point: token generation must be cryptographically random, storage must support atomic updates, and validation must prevent race conditions. Email delivery must happen within the TTL window, and it's the one constraint your code can't enforce directly. Treat DNS authentication (SPF and DKIM) and delivery monitoring as prerequisites you set up before launch, not afterthoughts.

Security tradeoffs of passwordless login

Magic links eliminate three attack vectors that passwords create:

  • No password storage: You don't store password hashes, so there's nothing to crack if your database leaks.
  • No credential stuffing: Attackers can't reuse leaked passwords from other breaches because there are no passwords.
  • No password reuse: Users can't use weak or reused passwords because they don't set one.

They introduce three new dependencies:

  • Email account becomes the authentication factor: If an attacker compromises the user's email, they can request magic links and gain access. The security of magic link login is only as strong as the security of the user's email account.
  • Token interception risk: The magic link URL contains a bearer token. Anyone who intercepts it (via insecure email, logged URLs, or Referer header leakage) can use it before the legitimate user does.
  • Delivery dependency: Passwords work even when email is down. Magic links require functioning email infrastructure with acceptable latency.

On balance, magic links trade password storage risk for email account compromise risk. For high-security environments, hardware keys or passkeys provide stronger guarantees.

Selecting magic links over passwords

Magic links are the right choice when:

  • Your user base has reliable email access and checks it regularly.
  • You have confidence in your email deliverability (verified domain, SPF/DKIM/DMARC configured, low bounce rates).
  • Your session persistence needs are compatible with a login flow that requires an email round trip.
  • You're optimizing for reduced friction on repeat logins (users don't need to remember or type a password).

Magic links are the wrong choice when:

  • Users can't complete magic link flows without immediate email access (factory floor workers, shared devices, offline environments).
  • Regulatory requirements mandate multi-factor authentication with hardware-backed keys.
  • Your threat model includes sophisticated phishing attacks where users might enter credentials on a fake page. Both magic links and OTP codes are vulnerable to real-time relay attacks where an attacker proxies the authentication flow.

The decision isn’t binary. Many production systems offer magic links as the default with email OTP codes as a fallback for users who prefer them or whose email infrastructure blocks link scanning.

Under the hood: magic link token validation

Token generation determines whether you can validate without a database lookup. This changes your architecture. HMAC-SHA256 tokens are stateless and validate without a database lookup. UUID tokens require database storage but allow immediate revocation.

import hmac
import hashlib
import time

SECRET_KEY = "your-256-bit-secret"

def generate_hmac_token(user_id, ttl_seconds=900):
expires_at = int(time.time()) + ttl_seconds
payload = f"{user_id}:{expires_at}"
signature = hmac.new(
SECRET_KEY.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
return f"{payload}:{signature}"

import secrets
import hashlib
import time

def generate_uuid_token(user_id, ttl_seconds=900):
raw_token = secrets.token_urlsafe(32) # 256 bits of entropy
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
expires_at = int(time.time()) + ttl_seconds

database.execute(
"INSERT INTO magic_links (token_hash, user_id, expires_at) VALUES (?, ?, ?)",
token_hash, user_id, expires_at
)
return raw_token # Send this in the email

HMAC tokens are stateless: you can validate them without a database lookup. The signature proves the token hasn't been tampered with, and the expiry timestamp is embedded in the payload. The tradeoff is that you can't revoke a token before it expires without maintaining a blacklist (which reintroduces state). UUID tokens require a database lookup but allow immediate revocation. If a user reports their email compromised, you can delete all active tokens for that user.

Database schema for link metadata

Store the hash of the token, not the token itself. If your database leaks, attackers can't use the stored hashes to authenticate. Use a schema like this:

Core token fields:

Column

Type

Constraint

token_hash

VARCHAR(64)

UNIQUE, NOT NULL

user_id

UUID

FOREIGN KEY, NOT NULL

expires_at

TIMESTAMP

NOT NULL

is_used

BOOLEAN

DEFAULT FALSE

Audit and security fields:

Column

Type

Purpose

id

UUID

Primary key

created_at

TIMESTAMP

Audit trail

request_ip

INET

Rate limiting and forensics

Index token_hash for fast lookup during validation. Index user_id if you need to query active tokens per user. The is_used boolean enforces single-use, but only if you update it atomically during validation.

Designing secure magic link URLs

The examples in this guide place the token in a URL query parameter: https://yourapp.com/auth/verify?token=7f3a9b2c.... Query parameters and path segments carry the same exposure, because both appear in server access logs and both leak via Referer headers when users navigate from your validation page to external links. Best practice guidance varies: some implementations put the token in a URL fragment, which browsers don't send to the server, and others use a POST-based confirmation step. Whichever placement you choose, set Referrer-Policy: no-referrer on the validation page and exclude the token from access logs.

Require TLS for every step of the flow: the token generation endpoint, the magic link URL, and the validation endpoint. The email provider should deliver over TLS (major providers do this by default). A token transmitted over HTTP is visible to anyone on the network path.

The URL should be single-use. Once clicked and validated, it must not work again. This is enforced in the validation logic, not the URL structure.

Verifying magic links for session access

Hash the token, look it up in the database, and atomically update is_used to true only if it's false. If the update succeeds, establish a session. If not, return an error.

# Pseudocode for atomic token validation
def validate_magic_link(raw_token):
token_hash = sha256(raw_token)

with database.transaction():
rows_updated = database.execute(
"UPDATE magic_links SET is_used = true "
"WHERE token_hash = ? AND is_used = false AND expires_at > NOW()",
token_hash
)

if rows_updated == 1:
user_id = database.query(
"SELECT user_id FROM magic_links WHERE token_hash = ?",
token_hash
)
return create_session(user_id)
else:
return error("Token expired, invalid, or already used")

The atomic update prevents race conditions. Two simultaneous requests with the same token can't both succeed because only one will flip is_used from false to true.

Preventing token replay attacks

Token replay is when an attacker (or a security scanner) uses a valid token before the legitimate user does. Single-use enforcement via atomic update is the primary defense. The is_used boolean with a WHERE clause ensures that even if two requests arrive simultaneously, only one succeeds.

Immediate invalidation matters because magic links are bearer tokens. Anyone with the URL can use it. If a token remains valid after first use, an attacker who intercepts it (via email compromise, log files, or browser history) can replay it indefinitely. Single-use enforcement limits the window of exposure to the time between email delivery and first click.

Securing magic link token lifecycles

Three controls govern the token lifecycle: TTL (time to live), single-use enforcement, and rate limiting. Each addresses a different attack vector.

Configuring magic link TTL

The OWASP Developer Guide says temporary links should have a short expiration time, but it doesn't set a specific number of minutes. NIST SP 800-63B allows up to 10 minutes for out-of-band authentication codes, and magic links follow similar logic because they function as possession checks. This guide recommends 10 to 15 minutes.

The 10 to 15 minute range balances security and usability. Shorter than 10 minutes and you risk token expiry during slow email delivery. Longer than 15 minutes and you extend the attack window without meaningful UX benefit.

Handle expiry during delivery delay by allowing the user to request a new link without friction. The error message should say "This link has expired. We've sent you a new one" and trigger a resend, not force the user back to the login page.

Invalidating tokens after first use

Mark the token as used immediately upon successful validation, in the same database transaction that establishes the session. This prevents the token from being replayed if the session establishment fails later in the request lifecycle.

Some implementations also invalidate tokens on failed validation attempts (wrong user, suspicious IP). This is optional and depends on your threat model. Invalidating on failure reduces the window for brute force but increases the chance of denial-of-service if an attacker can trigger validation failures for legitimate tokens.

Mitigating brute force login attacks

Rate limit both the token generation endpoint and the token validation endpoint. Token generation rate limiting prevents an attacker from spamming magic links to a victim's email address. A reasonable starting point is 3 requests per email address per hour, with a 24-hour cooldown after 10 requests.

Token validation rate limiting prevents brute force attacks on the token itself. Use at least 128 bits of entropy for magic link tokens, making brute force computationally infeasible, but rate limiting adds defense in depth. Limit validation attempts to 5 per IP address per minute, returning HTTP 429 (Too Many Requests) with a Retry-After header when the limit is exceeded.

Mandatory HTTPS for secure delivery

The TLS requirements from “Designing secure magic link URLs” apply to every step of the flow, including the validation endpoint. The only addition here is local testing.

Development environments often skip HTTPS for local testing. Use a tool like ngrok or Caddy to test with real certificates before deploying.

Evaluating magic links against one-time codes

The choice between magic links and OTP codes depends on your user experience priorities and threat model. Here's how they compare:

Factor

Magic Links

OTP Codes

User friction

One click

Retrieve and type 6-8 digits

Cross-device login

Works best on same device

Code is portable

Link scanner risk

Pre-fetch can consume token

No link to scan

Phishing resistance

Moderate (requires intercepting URL)

Moderate (fake page can relay code)

Delivery dependency

Email must arrive in TTL window

Email must arrive in TTL window

Implementation complexity

Simpler (no input UI)

Code generation and input UI needed

OTP adds more friction because users retrieve and manually enter a code, but the user stays in the application rather than switching contexts to email. Email security tools open links to scan them, which can trigger single-use token consumption before the real user clicks. Both methods function as possession checks, but they impose different operational requirements.

Optimizing magic link login journeys

Reduce friction by pre-filling the email address if you have it (from a cookie or previous session). Use a clear subject line like "Your login link for [App Name]" so users can find the email quickly. The landing page after clicking the link should be mobile-friendly and load fast.

Mitigate security scanner pre-fetching: Show a "Confirm Login" button after the link is clicked instead of immediately consuming the token. The token is only consumed when the user clicks the button, preventing automated scanners from invalidating it.

Threat model: magic links vs codes

Phishing: Magic links have moderate phishing resistance because the attacker must intercept a URL click, which requires compromising the email or DNS. OTP codes can be phished in real time by showing a fake login page that asks for the code and immediately relays it to the real service.

Link scanning: Magic links are vulnerable to security scanners that pre-fetch URLs in emails. Microsoft Defender for Office 365 Safe Links rewrites URLs and performs real-time verification when users click. Organizations reported seeing something systematically clicking the first link in the email immediately when emails are received. OTP codes have no link to scan, so they're immune to this attack vector.

Handling magic links on mobile devices

If you have a native mobile app, use deep linking to open the app directly when the user clicks the magic link. iOS calls this Universal Links, Android calls it App Links. Configure the magic link URL to work in both contexts: if the app is installed, open it via deep link. If not, fall back to a web-based validation page.

For mobile web, ensure the validation page is responsive and loads quickly. Users on mobile devices are more likely to abandon a slow-loading page than desktop users.

Reducing bounce risks in magic link systems

A bounced magic link email is a failed login. The user doesn't receive the link and doesn't know why. Bounce handling is a first-class reliability concern, not an edge case.

Handling token expiry during delay

If your delivery infrastructure introduces variable latency (shared IP queues, rate limits), some users will click links after the token has expired. The error handling flow determines whether this is a minor inconvenience or a support ticket.

When a user clicks an expired token, show a clear message: "This link has expired. We've sent you a new one." Send the new link when that click arrives, rather than forcing the user back to the login page. Resending only on the click is preferable to server-side auto-resend at expiry, because the click confirms the user is still trying to log in.

Some implementations add a grace period (e.g., tokens remain valid for 2 minutes after expires_at) to account for clock skew and delivery delays. This trades security for usability. The grace period extends the attack window, so use it only if your delivery latency is consistently near the TTL boundary.

Configuring SMTP for reliable delivery

SPF and DKIM are the prerequisites for reliable transactional email delivery. DMARC builds on them, but it's optional for basic delivery: a p=none policy only monitors and doesn't restrict anything. Without SPF or DKIM, major inbox providers (Gmail, Outlook) will throttle or reject your messages.

  • SPF (Sender Policy Framework): A DNS TXT record that lists which IP addresses are authorized to send email for your domain.
  • DKIM (DomainKeys Identified Mail): A cryptographic signature added to each email that proves it hasn't been tampered with in transit. The DNS record type depends on your provider: HubSpot has you publish two CNAME records, while Google issues a single TXT record. SPF and DMARC each use a TXT record.
  • DMARC (Domain-based Message Authentication, Reporting and Conformance): Builds on SPF and DKIM to specify what receivers should do if authentication fails (reject, quarantine, or monitor). DMARC allows a sender's domain to indicate that messages are protected by SPF and/or DKIM.

Google recommends authenticating messages with DKIM and SPF before enabling DMARC enforcement. send.io's domain verification flow walks through adding and verifying these records. The dashboard shows verification status for each, so you know when DNS propagation is complete and you can start sending. If you send over SMTP instead of the API, SMTP ports explained maps each port to its correct use case.

For transactional auth emails (magic links, OTP codes, password resets), a dedicated IP address isolates your sender reputation from other senders. Shared IP pools are fine for low-volume senders, but if you're sending thousands of magic links per day, a dedicated IP prevents another sender's poor practices from affecting your deliverability. send.io offers dedicated IPs on request.

Quantifying passwordless login lag

Delivery latency is a conversion metric, not just an infrastructure metric. Measure two intervals:

  1. Time from token generation to email delivery: How long between when your backend triggers the send and when the email provider confirms delivery?
  2. Time from click to session establishment: How long between when the user clicks the link and when they see the logged-in state?

The first interval is mostly outside your control (it depends on the email provider's queue and the recipient's inbox provider), but you can influence it with priority queue tagging and dedicated IPs. The second interval is entirely under your control: it depends on your validation endpoint's response time and your session establishment logic.

OTP codes have a similar delivery latency profile, but the user experience differs. With an OTP code, the user retrieves the email, reads the code, and types it into your app. This adds several seconds of manual work. With a magic link, the user clicks and waits for the redirect. The total time from email arrival to logged-in state is shorter for magic links, but only if your validation endpoint is fast.

Step-by-step guide to magic link integration

This section wires the pieces from earlier sections into one working flow. Token generation, TTL, and atomic validation are covered above. The steps below cover what those sections don't: sending the email through send.io, connecting the request and verify routes, and mapping failures to HTTP responses. If you're integrating with an existing auth system, adapt the route handlers to your framework.

Sending passwordless login messages

Here's how to send a magic link email using send.io's transactional email API:

curl -X POST https://api.sendio.run/emails \
-H "Authorization: Bearer $SENDIO_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: YOUR_UNIQUE_KEY_HERE" \
-d '{
"from": "auth@yourapp.com",
"to": "user@example.com",
"subject": "Your login link for YourApp",
"html": "<p>Click the link below to log in:</p><p><a href=\"https://yourapp.com/auth/verify?token=TOKEN_HERE">Log in to YourApp</a></p><p>This link expires in 15 minutes and can only be used once.</p>",
"text": "Click this link to log in: https://yourapp.com/auth/verify?token=TOKEN_HERE\n\n This link expires in 15 minutes and can only be used once.",
"priority": "otp"
}'

Generate a unique idempotency key per request (UUID or similar). The Idempotency-Key header prevents duplicate sends if your client retries due to a network timeout. send.io stores the key for 24 hours and returns the original result if the same key is used again. Without this header, a retry sends a duplicate email.

send.io lets you tag time-sensitive sends, such as OTP codes, so they queue ahead of bulk campaign sends. The examples in this guide use "priority": "otp" for that tag. Confirm the exact field name and value in the send.io API reference before you copy the sample, because an incorrect field name or value can cause the request to fail or the tag to be ignored.

Wiring request and verify routes

Here's a complete Flask wiring of the request and verify routes. It combines the token generator from "Under the hood: magic link token validation", the send.io call from the previous step, and the atomic validation logic from "Verifying magic links for session access". The GET route only renders a confirmation page, so security scanners that pre-fetch the link can't consume the token. Only the POST route validates it.

import os
import uuid
import requests
from flask import Flask, request, render_template, make_response

app = Flask(__name__)

@app.post("/auth/magic-link")
def request_magic_link():
user = find_user_by_email(request.json["email"])
if user:
raw_token = generate_uuid_token(user.id) # stores only the hash
link = f"https://yourapp.com/auth/verify?token={raw_token}"
requests.post(
"https://api.sendio.run/emails",
headers={
"Authorization": f"Bearer {os.environ['SENDIO_API_KEY']}",
"Idempotency-Key": str(uuid.uuid4()),
},
json={
"from": "auth@yourapp.com",
"to": user.email,
"subject": "Your login link for YourApp",
"html": f'<p><a href="{link}">Log in to YourApp</a></p>'
"<p>This link expires in 15 minutes and can only be used once.</p>",
"text": f"Click this link to log in: {link}",
"priority": "otp",
},
timeout=5,
)
# Identical response whether or not the email is registered
return {"message": "If that email is registered, we've sent a login link."}, 202

@app.get("/auth/verify")
def show_confirm_page():
# Never consumes the token: scanners that pre-fetch this URL stop here
response = make_response(render_template("confirm_login.html", token=request.args["token"]))
response.headers["Referrer-Policy"] = "no-referrer"
return response

@app.post("/auth/verify")
def confirm_login():
# validate_magic_link performs the atomic UPDATE shown earlier
# On failure, return the status codes and messages from the table below
return validate_magic_link(request.form["token"])

The confirm_login.html template renders a "Confirm Login" button inside a form that posts the token back to /auth/verify. The template and the find_user_by_email helper depend on your framework and user model, so adapt them to your stack. The priority field in the send.io payload uses the same unverified field name and value as the earlier curl example, so check both against the send.io API reference.

Managing invalid or expired login attempts

Map validation failures to appropriate HTTP status codes and error messages:

Failure State

HTTP Status

Error Code

User Message

Token expired

401

TOKEN_EXPIRED

"This link has expired. We've sent you a new one."

Token not found

401

INVALID_TOKEN

"This link is invalid or has already been used."

Token already used

401

TOKEN_ALREADY_USED

"This link has already been used. Request a new one."

Rate limit exceeded

429

RATE_LIMIT_EXCEEDED

"Too many attempts. Try again in X minutes."

Return 401 for an expired token because an expired token is an authentication failure. RFC 6750 uses 401 with error="invalid_token" for expired, revoked or malformed tokens. Rate limit violations return 429 (Too Many Requests).

Don't leak account existence in error messages. If the token doesn't exist in your database, return the same "invalid or expired" message whether the email address is registered or not. This prevents attackers from enumerating valid email addresses by requesting magic links and observing error responses.

Designing secure magic link notification flows

The email itself is part of the security model. A poorly designed email leaks information or confuses users.

Defining the auth email schema

Required fields for a magic link email:

  • Recipient: The user's email address (from your database).
  • Subject: Clear and specific: "Your login link for [App Name]". Don't include the token in the subject line (it will appear in email client previews and notification banners).
  • HTML body: A button or link with the magic link URL, plus fallback text link.
  • Text body: Plain text version with the full URL for email clients that don't render HTML.
  • Magic link URL: HTTPS, single-use, with the token in the query parameter.

Don't include the token in the subject line or preview text, and don't leak account existence in bounce messages. Don't include unsubscribe links (this is a transactional email, not marketing).

Optimizing React magic link templates

Here's a production-ready React Email template with mobile-responsive styling, a clear CTA button, and a fallback text link:

import { Html, Button, Text, Container } from "@react-email/components";

export default function MagicLinkEmail({ magicLinkUrl }) {
return (
<Html>
<Container style={{ maxWidth: "600px", margin: "0 auto", padding: "20px" }}>
<Text style={{ fontSize: "16px", marginBottom: "20px" }}>
Click the button below to log in to YourApp:
</Text>
<Button
href={magicLinkUrl}
style={{
backgroundColor: "#007bff",
color: "#ffffff",
padding: "12px 24px",
borderRadius: "4px",
textDecoration: "none",
display: "inline-block",
}}
>
Log in to YourApp
</Button>
<Text style={{ fontSize: "14px", marginTop: "20px", color: "#666" }}>
This link expires in 15 minutes and can only be used once.
</Text>
<Text style={{ fontSize: "14px", color: "#666" }}>
If the button doesn't work, copy and paste this link into your browser:
</Text>
<Text style={{ fontSize: "12px", wordBreak: "break-all", color: "#007bff" }}>
{magicLinkUrl}
</Text>
</Container>
</Html>
);
}

This template is mobile-responsive (max-width 600px, inline styles for email client compatibility), includes a clear call-to-action button, provides a fallback text link, and sets expectations about expiry and single-use.

Optimizing magic link deliverability

send.io's webhook system lets you monitor delivery, bounce, and complaint events in real time. Configure send.io webhooks to monitor delivery events:

curl -X POST https://api.sendio.run/webhooks \
-H "Authorization: Bearer $SENDIO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://yourapp.com/webhooks/sendio",
"events": ["delivered", "bounced", "complained"]
}'

The webhook payload includes the message ID, event type, timestamp, and recipient email. For bounce events, it also includes a bounce object with the bounce type (Permanent or Transient), subtype, and diagnostic code. This lets you distinguish between a hard bounce (email address doesn't exist) and a soft bounce (mailbox full, temporary server issue).

For magic link emails, monitor bounce rates and suppress addresses that hard bounce. send.io automatically suppresses bounce and complaint addresses, but you can also manage suppression lists manually via the API.

Before committing to an integration, send a test magic link to an address you control using the transactional email API and the code examples above. Then inspect the delivered webhook payload and its timestamp to measure delivery latency for your own domain and recipient mailbox provider.

FAQs

How long should magic link tokens be valid?

Magic link tokens should expire within 10 to 15 minutes. The OWASP Developer Guide says temporary links should have a short expiration time but doesn't specify a number, so this guide recommends this range. Use 10 minutes if your delivery infrastructure is fast, 15 minutes if you're on shared IP queues with variable latency.

What happens if a user clicks an expired magic link?

The validation endpoint returns a 401 error with code TOKEN_EXPIRED. Show a message like "This link has expired. We've sent you a new one" and automatically trigger a resend rather than forcing the user back to the login page.

Can magic links be used multiple times?

No. Magic links are single-use tokens that invalidate immediately after first click. The validation logic atomically updates an is_used flag, so only the first request succeeds.

How do you prevent magic link enumeration attacks?

Return identical responses whether the email address is registered or not: "If that email is registered, we've sent a login link." Rate limit the token generation endpoint to 3 requests per email per hour to prevent bulk enumeration attempts.

Should magic links work across different devices?

Magic links work best when the user checks email on the same device they're logging in on. For cross-device flows, consider OTP codes instead because users can read a code on one device and type it on another.

Key terms glossary

Magic link: A single-use URL containing a cryptographically random token, delivered by email, that authenticates a user when clicked. Also called a passwordless email login link.

Token hash: The SHA-256 hash of the raw token, stored in the database instead of the token itself. If the database leaks, attackers can't use stored hashes to authenticate.

TTL (time to live): The duration a token remains valid, measured from creation to expiry. For magic links, the recommended TTL is 10 to 15 minutes.

Token replay: An attack where an adversary uses a valid token before the legitimate user does, typically by intercepting the email or pre-fetching the link. Prevented by single-use enforcement.

HMAC-SHA256: A cryptographic hash function that combines a secret key with a message payload to produce a signature. Used for stateless magic link tokens that can be validated without a database lookup.

UUID (universally unique identifier): A 128-bit random identifier, often used as a stateful magic link token stored in the database. Requires a lookup to validate but allows immediate revocation.

Idempotent retry: A retry mechanism that produces the same result as the original request, preventing duplicate side effects. For email, an idempotency key ensures a retry doesn't send a duplicate message.

Suppression list: A list of email addresses that should not receive sends, typically because they hard bounced, complained, or unsubscribed. send.io automatically suppresses bounce and complaint addresses.

DKIM (DomainKeys Identified Mail): An email authentication method that adds a cryptographic signature to each message, proving it hasn't been tampered with in transit. The DNS record type depends on the provider: HubSpot uses two CNAME records, while Google uses a single TXT record.

SPF (Sender Policy Framework): An email authentication method that specifies which IP addresses are authorized to send email for a domain. Requires a single TXT record in DNS.

DMARC (Domain-based Message Authentication, Reporting and Conformance): An email authentication policy that builds on SPF and DKIM to specify what receivers should do if authentication fails (reject, quarantine, or monitor). Requires a TXT record in DNS.