Adding email to a vibe-coded stack — magic links for login and transactional messages for receipts — is where demos die in spam folders and Supabase auth callbacks 404 on wrong domains. AI agents wire Resend or SendGrid in ten minutes and skip DKIM, redirect URLs, and idempotent welcome sends. This tutorial walks magic link auth plus transactional patterns for Next.js App Router with production checks. Updated November 2026.

Prerequisites: working app shell from the vibe coding roadmap, auth baseline from add auth to a vibe-coded Next.js app, and deploy on custom domain via deploy to Vercel. Run the launch checklist item on email before public beta.
Table of contents
- Email architecture choices
- Step 1 — Provider and domain setup
- Step 2 — Magic link auth flow
- Step 3 — Transactional templates
- Step 4 — Server routes and security
- Step 5 — Testing and deliverability
- AI-generated email bugs
- FAQ
Email architecture choices
2026 vibe stacks usually pick:
- Supabase Auth magic links — auth sends email; you customize SMTP or use Supabase defaults (limited branding)
- NextAuth / Auth.js + Resend — full control of template and provider
- Clerk / WorkOS — hosted auth emails included — less tutorial focus here
- Resend + custom token — roll your own magic link (only if you understand JWT expiry)
| Pattern | Pros | Cons |
|---|---|---|
| Supabase built-in magic link | Fast; integrates with RLS user | Template control limited on free tier |
| Auth.js Email provider + Resend | Flexible templates, Next-native | More config surface |
| Custom magic token | Total control | Easy to get crypto wrong |
This guide emphasizes Supabase Auth magic links plus Resend for transactional (welcome, invoice, alert) — common solo stack.
Step 1 — Provider and domain setup
- Create Resend account; verify sending domain (subdomain like
mail.yourdomain.comrecommended) - Add DNS records: SPF, DKIM, optional DMARC — wait for green check in dashboard
- Store
RESEND_API_KEYin Vercel production and preview env (different keys if desired) - Set
NEXT_PUBLIC_SITE_URLto production URL — auth callbacks depend on it - In Supabase Dashboard → Authentication → URL Configuration: set Site URL and redirect allowlist
Prompt: “Configure Supabase auth redirect URLs for https://app.example.com/auth/callback. Add RESEND_API_KEY server-only. Do not expose keys in client components.”
Step 2 — Magic link auth flow
Supabase magic link flow:
- User enters email on login page
- Client calls
supabase.auth.signInWithOtp({ email, options: { emailRedirectTo } })} - User clicks link in email; Supabase validates token
- Callback route exchanges session; redirect to dashboard
- Middleware refreshes session cookie on subsequent requests
Critical emailRedirectTo must match allowlist exactly — including trailing slash consistency. AI often hardcodes localhost; production magic links then fail silently.
Custom SMTP: Supabase → Project Settings → Auth → SMTP with Resend credentials for branded auth emails. Template variables documented in Supabase auth email docs.

Step 3 — Transactional templates
Separate auth emails from product emails:
- Welcome — after first signup (trigger from webhook or post-confirm route once)
- Receipt / invoice — after Stripe
checkout.session.completed - Alerts — usage threshold, failed payment — tie to Stripe webhooks
- Support ack — contact form received
Resend React Email pattern in Next.js:
- Templates in
emails/Welcome.tsxusing @react-email/components - Server route or server action calls
resend.emails.send({ from, to, subject, react: WelcomeEmail({ name }) }) - From address on verified domain:
hello@mail.yourdomain.com
Idempotency: store welcome_sent_at on user row — webhook retries must not send five welcomes. Same lesson as Stripe webhook idempotency.
Step 4 — Server routes and security
- Send email only from server — API route, server action, or Edge Function
- Rate limit
/api/auth/magic-linkand contact endpoints per IP and email - Validate email format; do not leak “user not found” vs “sent” if enumeration matters — uniform success message
- Log message id from Resend; never log full magic link URLs in production logs
- Admin “resend welcome” behind role check
Cross-check auth middleware from the auth tutorial — email login does not replace session checks on dashboard routes.
Step 5 — Testing and deliverability
- Send test to Gmail, Outlook, and one mobile client
- Check spam placement — missing DKIM is the usual culprit
- Click magic link on mobile mail app — session persists in app browser
- Test expired link error copy
- Stripe test payment → confirm receipt email within 60 seconds
Use Resend logs for bounces; suppress repeated sends to hard bounces. Add monitoring alert if send error rate spikes.
AI-generated email bugs
| Bug | Symptom | Fix |
|---|---|---|
| RESEND_API_KEY in client | Key scraped from bundle | Server-only import |
| Wrong redirect URL | Magic link lands on 404 | Site URL + allowlist sync |
| No idempotency on welcome | Duplicate emails on webhook retry | DB flag before send |
| From noreply@gmail.com | Spam folder | Verified custom domain |
| HTML-only broken on mobile | Ugly plaintext fallback | React Email + preview text |
Wire CI smoke test that mocks Resend in AI code tests — assert send called once per event.
Alternatives: Postmark, SendGrid, AWS SES
Resend wins vibe-coding tutorials for DX; Postmark excels deliverability support; SES wins at scale on AWS. Switching cost is mostly template port and env vars — keep send logic behind one sendEmail() wrapper your agent does not duplicate per feature.
Compliance and unsubscribe
Transactional emails (receipts, magic links) generally skip marketing unsubscribe — product emails blurring into newsletters need List-Unsubscribe headers and consent. When in doubt, separate marketing@ subdomain from auth@ and billing@.
Custom SMTP for Supabase auth emails
Default Supabase email works for first login test; production branding needs custom SMTP. Resend SMTP credentials in Supabase auth settings:
- Host, port, user, password from Resend SMTP docs
- Sender email on verified domain
- Customize magic link template with product name and support link
- Test OTP expiry message renders in plain text fallback
Prompt: “Configure Supabase to use custom SMTP for auth emails. Keep magic link template minimal — product name, one sentence, single CTA button styled inline CSS only. No external stylesheet links in email HTML.”
Connecting Stripe webhooks to email
Receipt email belongs in webhook handler after idempotency check:
- Verify Stripe signature on raw body
- Parse
checkout.session.completed - Lookup user by customer id; check
receipt_sent_atnull - Send React Email template with line items from session
- Set
receipt_sent_atbefore returning 200
Duplicate webhook delivery without idempotency spams users — same pattern as payment state bugs in Stripe tutorials. Cross-read payment prompts for event types beyond checkout if you use subscriptions.
Local development email traps
Localhost magic links fail on phones unless tunneling. Options:
- Mailpit / Inbucket — catch emails locally without sending
- ngrok or Cloudflare tunnel — test real links on device
- Staging deploy — authoritative pre-prod email QA
AI agents hardcode http://localhost:3000 in emailRedirectTo — grep before every production deploy. Add CI check that fails if localhost appears outside test files.
Monitoring email health
| Signal | Tool | Action threshold |
|---|---|---|
| Bounce rate | Resend dashboard | Investigate if >2% daily |
| Auth email latency | Supabase logs | Alert if p95 >30s |
| Magic link click-through | Product analytics | Drop may mean spam folder |
| Send API errors | Sentry on server route | Page on 5xx spike |
Transactional template library
Standardize templates early — agents invent new HTML per email otherwise:
| Template | Trigger | Key fields |
|---|---|---|
| MagicLink | Auth OTP | expiry note, support email |
| Welcome | First signup | first action CTA deep link |
| Receipt | checkout.session.completed | amount, last4, manage billing link |
| PaymentFailed | invoice.payment_failed | update payment method URL |
| ContactAck | Form submit | expected response time |
Store in emails/ with shared Layout wrapper — logo, footer address, unsubscribe only on marketing subset. Prompt: “All transactional emails use emails/components/Layout.tsx — no standalone HTML documents.”
Auth.js Email provider alternative
Not on Supabase Auth? Auth.js with Resend provider:
- Install
@auth/coreand configure Email provider - Custom sendVerificationRequest calling Resend SDK
- Session strategy JWT or database per your stack
- Align
AUTH_URLwith production domain
Same DNS and rate-limit rules apply. Choose one auth email path — dual systems send duplicate magic links and confuse users.
Deliverability deep checks before launch
Beyond DNS green checks:
- Send from subdomain (
mail.domain.com) — protects root domain reputation if marketing spams later - Set DMARC p=none initially, move to quarantine after week of clean sends
- Avoid link shorteners in auth emails — spam filters flag them
- Plain text part included — multipart/alternative in Resend templates
- Preview text in template — not empty or “View in browser” only
Seed Gmail Postmaster Tools for domain when volume exceeds fifty daily — early reputation data prevents crisis mode at growth spike.
Marketing vs transactional separation
Adding newsletter checkbox at signup? Split infrastructure:
- Transactional: auth, receipts — no unsubscribe required; send regardless of marketing opt-out
- Marketing: product updates — separate list in Resend Audiences or provider equivalent
- Never mix — unsubscribing from newsletter must not block magic links
Prompt agents explicitly: “Welcome email is transactional post-confirm only. Newsletter uses separate double opt-in flow.” One conflated stream creates legal and deliverability mess.
FAQ
Magic link or password for B2B SaaS?
Magic links reduce support burden; some enterprises prefer SSO later. Start magic link; add Google OAuth when requested.
Can I use Resend free tier for production?
Often yes at low volume — verify current limits and domain verification requirements.
Supabase email rate limits?
Built-in provider throttles; custom SMTP via Resend raises ceiling — monitor abuse on public signup forms.
How long should magic links last?
Supabase defaults are documented in auth settings — balance UX vs security; never infinite.
Why do emails work locally but not on Vercel?
Missing env vars on production, or Site URL still localhost in Supabase dashboard.
Should I use Edge or Node runtime for send?
Node serverless for Resend SDK compatibility unless docs specify edge — verify before shipping.
Can I use one Resend account for multiple projects?
Yes — separate domains per project; never share verified domain between unrelated brands without tracking reputation separately.
What about SendGrid or Amazon SES?
Same architecture — magic link plus transactional split, DNS verification, server-only keys. Resend examples port directly with SDK swap.
Email completes the auth and revenue loop — without deliverability, the rest of your vibe-coded stack is a local demo with a custom domain. Treat DNS and callback URLs as launch blockers equal to RLS.
Soft CTA: Verify your domain in Resend tonight, send one magic link to your phone, and click it on cellular data — not WiFi localhost fantasy. Then add one transactional template tied to a real Stripe test event. Email done right is invisible; email done wrong is your entire launch.
Related reading on Vibe Coding Engineer
Continue with the vibe coding roadmap, the 2026 starter stack, and the Month 2 reading list. Each guide is written for builders who want outcomes, not hype — Free Code Hustle style. Bookmark this page and ship the next thin slice before you open another tab of tool comparisons.
When you are ready for monetization and ops, pair this article with Month 3 hubs on payments, security, and production monitoring. The goal is a compounding library: every post should make the next deploy safer, faster, or more useful to a real user.
