Invite tokens, pending invites that do not duplicate, seat limits that hold under concurrency, accepting with a different email address and revoking, with a TypeScript service on Encore.

Team invitations connect billing, authentication and email in one flow. An admin types an address, someone clicks the link days later, and by then they may have signed up with another email, the invite may be revoked or the plan may be out of seats.
This guide covers the data model, the token, seat limits under concurrent invites and the accept step, and builds it as a TypeScript service.
The organization, the invited address, the role the person will get, who sent it, a hashed token and timestamps for expiry, acceptance and revocation. Store the token as a SHA-256 hash generated from 32 random bytes with crypto.randomBytes, since an unhashed token in a database dump is a working invitation into a customer's workspace. Seven days is a common expiry.
One pending invitation per address and organization keeps the members page clean and stops repeated clicks on "Invite" from sending five links. A partial unique index on (org_id, lower(email)) WHERE accepted_at IS NULL AND revoked_at IS NULL enforces that while still allowing a new invite after the old one is accepted or revoked. A repeat invite then becomes a resend: rotate the token on the existing row and email the new link.
Count members plus pending invitations against the plan's seat limit, otherwise an admin can send 50 invites on a 10-seat plan and the overflow only shows up when people accept. The check and the insert must run in one transaction with the organization row locked using SELECT ... FOR UPDATE, which serializes invites for that organization so two admins inviting at the same moment cannot both pass a check that only one of them should pass.
The invitee signs in or signs up first, then the accept call carries the token and the user's identity. Claim the invitation with an UPDATE ... WHERE accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now() RETURNING, create the membership with the role from the invitation and do both in one transaction. Insert the membership with ON CONFLICT DO NOTHING, so a user who is already a member does not get an error, only a link to the workspace.
Decide whether the signed-in email must match the invited address. Business tools usually require it, which protects against a forwarded link landing in the wrong account, and the OWASP Authorization Cheat Sheet advice to deny by default points the same way. Consumer apps often skip it. Either way, never take the role from the request, only from the stored invitation.
Revoking sets revoked_at, which makes the claim query match nothing and frees the seat at once. Expired invitations need no job to stop working, since the claim query checks expires_at, but a nightly cleanup keeps the pending list from filling up with dead rows and is a good moment to notify admins whose invites expired unused.
Encore is a backend framework with built-in infrastructure, so the membership tables, the invite email queue and the provider key are declared in the TypeScript service that owns invitations. Organizations, members and invitations live in an Encore Postgres database, invite emails go through a Pub/Sub topic, and the email key is an Encore secret. The endpoints below are internal and called from your authenticated API layer, which supplies the acting user from the auth handler.
Run in your terminal to get started locally.
-- teams/migrations/1_create_teams.up.sql
CREATE TABLE organizations (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL,
seat_limit INT NOT NULL
);
CREATE TABLE memberships (
org_id BIGINT NOT NULL REFERENCES organizations (id),
user_id TEXT NOT NULL,
role TEXT NOT NULL CHECK (role IN ('admin', 'member')),
PRIMARY KEY (org_id, user_id)
);
CREATE TABLE invitations (
id BIGSERIAL PRIMARY KEY,
org_id BIGINT NOT NULL REFERENCES organizations (id),
email TEXT NOT NULL,
role TEXT NOT NULL CHECK (role IN ('admin', 'member')),
invited_by TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
accepted_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX invitations_one_pending
ON invitations (org_id, lower(email))
WHERE accepted_at IS NULL AND revoked_at IS NULL;
// teams/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("teams");
// teams/invitations.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic, Subscription } from "encore.dev/pubsub";
import { secret } from "encore.dev/config";
import { createHash, randomBytes } from "node:crypto";
const db = new SQLDatabase("teams", { migrations: "./migrations" });
const resendKey = secret("ResendAPIKey");
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
type Role = "admin" | "member";
interface InviteEmail {
email: string;
orgName: string;
token: string;
}
const inviteEmails = new Topic<InviteEmail>("invite-emails", { deliveryGuarantee: "at-least-once" });
export const invite = api(
{ expose: false },
async (p: { orgId: number; actorId: string; email: string; role: Role }): Promise<{ invitationId: number }> => {
await using tx = await db.begin();
const actor = await tx.queryRow<{ role: Role }>`
SELECT role FROM memberships WHERE org_id = ${p.orgId} AND user_id = ${p.actorId}`;
if (actor?.role !== "admin") throw APIError.permissionDenied("only admins can invite");
// Lock the organization so concurrent invites are checked one at a time.
const org = await tx.queryRow<{ name: string; seat_limit: number }>`
SELECT name, seat_limit FROM organizations WHERE id = ${p.orgId} FOR UPDATE`;
if (!org) throw APIError.notFound("organization not found");
const used = await tx.queryRow<{ n: number }>`
SELECT ((SELECT count(*) FROM memberships WHERE org_id = ${p.orgId})
+ (SELECT count(*) FROM invitations
WHERE org_id = ${p.orgId} AND accepted_at IS NULL AND revoked_at IS NULL
AND expires_at > now() AND lower(email) <> lower(${p.email})))::int AS n`;
if (used!.n >= org.seat_limit) throw APIError.resourceExhausted("no seats left on this plan");
const token = randomBytes(32).toString("base64url");
// A second invite to the same address rotates the token on the pending row.
const row = await tx.queryRow<{ id: number }>`
INSERT INTO invitations (org_id, email, role, invited_by, token_hash, expires_at)
VALUES (${p.orgId}, ${p.email}, ${p.role}, ${p.actorId}, ${sha256(token)}, now() + interval '7 days')
ON CONFLICT (org_id, lower(email)) WHERE accepted_at IS NULL AND revoked_at IS NULL
DO UPDATE SET token_hash = EXCLUDED.token_hash, role = EXCLUDED.role,
invited_by = EXCLUDED.invited_by, expires_at = EXCLUDED.expires_at
RETURNING id`;
await tx.commit();
await inviteEmails.publish({ email: p.email, orgName: org.name, token });
return { invitationId: row!.id };
},
);
export const accept = api(
{ expose: false },
async (p: { token: string; userId: string; userEmail: string }): Promise<{ orgId: number; role: Role }> => {
await using tx = await db.begin();
const inv = await tx.queryRow<{ id: number; org_id: number; role: Role; email: string }>`
UPDATE invitations SET accepted_at = now()
WHERE token_hash = ${sha256(p.token)}
AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now()
RETURNING id, org_id, role, email`;
if (!inv) throw APIError.notFound("invitation is invalid, expired or revoked");
if (inv.email.toLowerCase() !== p.userEmail.toLowerCase()) {
throw APIError.permissionDenied("this invitation was sent to a different email address");
}
await tx.exec`
INSERT INTO memberships (org_id, user_id, role)
VALUES (${inv.org_id}, ${p.userId}, ${inv.role})
ON CONFLICT (org_id, user_id) DO NOTHING`;
await tx.commit();
return { orgId: inv.org_id, role: inv.role };
},
);
export const revoke = api(
{ expose: false },
async (p: { orgId: number; actorId: string; invitationId: number }): Promise<void> => {
const actor = await db.queryRow<{ role: Role }>`
SELECT role FROM memberships WHERE org_id = ${p.orgId} AND user_id = ${p.actorId}`;
if (actor?.role !== "admin") throw APIError.permissionDenied("only admins can revoke");
await db.exec`
UPDATE invitations SET revoked_at = now()
WHERE id = ${p.invitationId} AND org_id = ${p.orgId} AND accepted_at IS NULL`;
},
);
export const _sendInvite = new Subscription(inviteEmails, "send-invite-email", {
handler: async ({ email, orgName, token }) => {
const res = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: { Authorization: `Bearer ${resendKey()}`, "Content-Type": "application/json" },
body: JSON.stringify({
from: "Example <team@example.com>",
to: email,
subject: `You are invited to ${orgName}`,
html: `<p><a href="https://app.example.com/invite#token=${token}">Join ${orgName}</a>. The link expires in 7 days.</p>`,
}),
});
if (!res.ok) throw new Error(`email provider returned ${res.status}`);
},
});
The seat query leaves out the pending invite for the same address, so a resend does not count that person twice. If the email check fails in accept, the thrown error rolls back the claim through await using, and the invitation stays pending for the right person. Set the email key with encore secret set --type dev,local ResendAPIKey and once more for production.
encore run starts Postgres locally and applies the migration, so you can create an organization with two seats, fire three invites at once and watch the third fail with resource_exhausted in the local trace. The cleanup of expired invites fits a nightly Encore cron job, which is managed by the Encore platform and runs in deployed environments rather than locally.
Invitation logic touches billing and permissions, so it is a place where agent changes deserve a local run: a change to the seat rule or the accept check can be exercised against real rows in the same session it was written.
Best fit: SaaS products adding multi-user workspaces that want invitations, seats and memberships enforced by their own Postgres database.
An admin enters an email address and a role, the backend stores a pending invitation with a hashed random token and emails a link. When the invitee signs in and opens the link, the backend checks the token, creates the membership and marks the invitation accepted.
Yes, for business tools. Requiring a match is safer where admins expect access to land on a specific work address, while allowing any signed-in user who holds the link is friendlier for consumer and small-team apps. Make it an explicit rule rather than an accident.
Count current members plus pending invitations, and do the count and the insert in one transaction after locking the organization row with SELECT ... FOR UPDATE. Without the lock, two admins inviting at the same moment can both pass the check and exceed the limit.
Store organizations, memberships and invitations in an Encore Postgres database, send invite emails from a Pub/Sub subscriber, and run the seat check and insert inside one transaction. encore run starts Postgres locally so the whole invite and accept flow runs on your machine.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.