Building the Viral Loop: Team Invitations and Secure Magic Links
Karl Gusta
Instructor & Founder
The Viral Engine: Why Invitations Matter
In a multi-tenant SaaS, your existing users are your best marketers. When an admin invites their teammates to join a workspace, they are doing the work of user acquisition for you. This "Viral Loop" is the most cost-effective way to grow a SaaS. However, an invitation system is more than just sending an email; it is a sensitive security workflow.
You need to ensure that an invitation sent to colleague@company.com cannot be hijacked by someone else. You also need to handle the flow for users who don't have an account yet—taking them from an email click to a registered, verified member of a specific organization in one seamless motion.
In this guide, we will implement a secure invitation system. We will cover generating unique invitation tokens, sending them via Resend, and using Magic Links to allow new users to join your SaaS without ever typing a password.
The Problem: The Security of Open Doors
The biggest risk with invitations is "Token Exposure." If your invitation links are predictable (like /join/123), attackers can brute-force their way into private organizations. Furthermore, if the invitation link does not expire, an old email could grant access to a former employee months later.
The second challenge is user friction. If a teammate receives an invite but has to go through a complex five-step registration process, they might give up. We need a "One-Click Join" experience that handles authentication and organization membership simultaneously.
!
The Shift: Token-Based Identity Verification
The shift is moving from static IDs to cryptographically secure tokens. Instead of linking to an organization ID, we link to a one-time invitationToken stored in MongoDB. This token is a random, high-entropy string that is nearly impossible to guess.
We will use NextAuth's Email Provider to handle the Magic Link logic. When a user clicks an invite link, we verify the token, check if the email matches the intended recipient, and then use NextAuth to sign them in. This ensures that the person joining the team is exactly who the admin intended.
Securing Your SaaS provides the foundational auth setup required for this advanced workflow.
Deep Dive: The Invitation Workflow
1. Generating and Storing the Invitation
When an admin invites a user, we create a document in an invitations collection. This document acts as a temporary "pending" state.
The Workflow:
- Admin Input: Admin enters an email and selects a role (e.g., Member).
- Token Generation: Use the Node.js
cryptomodule to generate a random hex string. - Expiration: Set an
expiresAttimestamp (e.g., 48 hours from now). - Storage: Save the email, orgId, role, and token in MongoDB.
2. Sending the Magic Invite via Resend
The email should be clear and professional. It serves as the user's first impression of your SaaS.
The Reasoning:
We use React Email to build a template that includes the organization's name and a prominent "Join Team" button. This button links to a specialized route: /api/invite/verify?token=XYZ.
typescript// app/actions/inviteActions.ts "use server" import crypto from "crypto"; import clientPromise from "@/lib/mongodb"; import { sendInviteEmail } from "@/lib/mail"; export async function inviteTeammate(orgId: string, email: string, role: string) { const token = crypto.randomBytes(32).toString("hex"); const expires = new Date(Date.now() + 48 * 60 * 60 * 1000); // 48 hours const db = (await clientPromise).db(); await db.collection("invitations").insertOne({ token, orgId, email, role, expires, status: "pending" }); await sendInviteEmail(email, token, orgId); }
3. The Verification and Auto-Join Logic
When the recipient clicks the link, your api/invite/verify route takes over. This is where the magic happens.
The Logic Chain:
- Find: Look up the token in MongoDB.
- Validate: Check if the token exists, is not expired, and has not been used.
- Upsert User: If the user doesn't exist, create a shell user account.
- Join: Create a
membershipsdocument linking the user to the organization with the specified role. - Clean Up: Mark the invitation as "accepted" or delete it.
- Sign In: Use NextAuth to trigger an automatic login for the user.
4. Magic Links for Passwordless Auth
To make the flow even smoother, we use NextAuth's Magic Link feature. If the user clicking the invite link is new, they don't need to set a password. NextAuth sends a second "Sign In" email that verifies their device. This "Passwordless" approach is increasingly popular in modern B2B SaaS because it is both more secure and more convenient than traditional passwords.
Key Benefits and Learning Outcomes
- Viral Growth: Your app grows automatically as teams expand.
- Frictionless Onboarding: Users can join a team in seconds without managing new credentials.
- Granular Control: Admins can see who has accepted invites and revoke pending ones if necessary.
- High Security: Cryptographic tokens and expiration dates prevent unauthorized access.
Common Mistakes to Avoid
- Reusing Tokens: Always invalidate a token the moment it is used. Allowing a token to be used twice is a major security flaw.
- Case Sensitivity in Emails: Users often type
Email@Company.combut the invite was sent toemail@company.com. Always.toLowerCase()your email strings before comparing them. - Leaking Org Names: Don't put the organization name in the URL parameters. Use the token to look up the organization name on the server to avoid information disclosure.
- Ignoring the Expiry Check: A 48-hour window is standard. If you don't check the expiry, you leave a permanent backdoor into your users' organizations.

Pro Tips and Best Practices
- Pending Invites List: Build a UI in the "Team Settings" page where admins can see a list of pending invites. This gives them confidence that the emails were sent.
- Domain Whitelisting: For enterprise clients, you can allow anyone with a
@client-company.comemail to join the organization automatically without a specific invite. - Personalized Subject Lines: Use the inviting admin's name in the subject line (e.g., "John invited you to the Marketing Team on AcmeSaaS"). This significantly increases open rates.
- Invite Reminders: Use a background job to send a one-time reminder email 24 hours before an invitation expires.
How This Fits Into the Zero to SaaS Journey
We have moved from individual accounts to multi-tenant organizations. Now, we have built the pipes that allow those organizations to fill up with users. In the Zero to SaaS journey, this is the transition from a "Single User Tool" to a "Team Platform."
By mastering the invitation flow, you have unlocked the primary engine for B2B growth. You are now ready to handle complex team structures and provide the professional experience that business customers expect.
Real-World Use Case: The Project Collaboration Hub
Imagine a SaaS like Notion or Slack.
- The Trigger: A Project Manager wants to add three designers to a new project.
- The Flow: They enter the emails in the "Invite" modal.
- The Experience: The designers receive a beautifully branded email. They click one button and are instantly dropped into the specific project dashboard with "Member" permissions.
- The Result: Zero support tickets, zero password resets, and three new active users for your platform.

Action Plan: What to Build Next
Build your viral engine today:
- Schema: Add an
invitationscollection to your MongoDB database. - Logic: Create a Server Action to generate a token and save the invite.
- Email: Design an invitation template using React Email and Resend.
- Verify: Create the
/api/invite/verifyroute to handle the token check and membership creation. - UI: Add a "Invite Teammate" button and a "Pending Invites" list to your Organization Settings page.
Your SaaS is now ready for teamwork.
Scale Your Team Features
Invitations are just the start of the team experience. Once users are in, you can explore features like Team Activity Feeds, Shared Billing, and Collaborative Editing.
If you want the complete, pre-tested invitation logic—including the token verification API and the email templates—you can find it in our advanced modules.
Ready for the next step? Check out the Advanced Multi-tenant Architecture guide to see how to manage large-scale team environments.