Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(invite): switch to verifyOtp + /auth/confirm — invite mails use hash-flow, not PKCE (#129)

Gökhan Geyikbc81dd5e2362
diff --git a/web/src/app/auth/confirm/route.ts b/web/src/app/auth/confirm/route.ts
new file mode 100644
index 000000000..981fde40f
--- /dev/null
+++ b/web/src/app/auth/confirm/route.ts
@@ -0,0 +1,59 @@
+import { NextResponse } from 'next/server';
+import { createClient } from '@/lib/supabase/server';
+import type { EmailOtpType } from '@supabase/supabase-js';
+
+/**
+ * GET /auth/confirm — server-side OTP verification for email-driven auth flows.
+ *
+ * Supabase's default `{{ .ConfirmationURL }}` template variable points at
+ * `https://<project>.supabase.co/auth/v1/verify?token=...&redirect_to=...`,
+ * which returns the session in the URL hash fragment (`#access_token=...`).
+ * Hash fragments aren't visible to server components, so the session never
+ * makes it into our cookies — the user lands on the destination page
+ * still "signed out" from the server's perspective and bounces to /sign-up.
+ *
+ * The fix is the standard Supabase + Next.js SSR pattern: customize the
+ * email templates to point here with `{{ .TokenHash }}` + `{{ .Type }}`,
+ * verify the OTP server-side, set the session via the auth helper's
+ * cookie machinery, then 302 to the original destination.
+ *
+ * Expected template URL:
+ * {{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=invite&redirect_to={{ .RedirectTo }}
+ *
+ * Works for every email type Supabase ships — invite, signup, recovery,
+ * magiclink, email_change. The type comes from the template, not from us.
+ */
+export async function GET(request: Request) {
+ const { searchParams, origin } = new URL(request.url);
+ const tokenHash = searchParams.get('token_hash');
+ const type = searchParams.get('type') as EmailOtpType | null;
+ const rawRedirect = searchParams.get('redirect_to') ?? searchParams.get('next');
+ const redirectTarget = resolveRedirect(rawRedirect, origin);
+
+ if (!tokenHash || !type) {
+ return NextResponse.redirect(`${origin}/sign-in?error=auth_confirm_missing_params`);
+ }
+
+ const supabase = await createClient();
+ const { error } = await supabase.auth.verifyOtp({ type, token_hash: tokenHash });
+
+ if (error) {
+ return NextResponse.redirect(
+ `${origin}/sign-in?error=auth_confirm_failed&reason=${encodeURIComponent(error.message)}`,
+ );
+ }
+
+ return NextResponse.redirect(redirectTarget);
+}
+
+/**
+ * Accept either a full URL (already absolute, e.g. when Supabase expands
+ * `{{ .RedirectTo }}` we pass during inviteUserByEmail) or a path; default
+ * to /dashboard if neither was provided.
+ */
+function resolveRedirect(value: string | null, origin: string): string {
+ if (!value) return `${origin}/dashboard`;
+ if (/^https?:\/\//i.test(value)) return value;
+ if (value.startsWith('/')) return `${origin}${value}`;
+ return `${origin}/dashboard`;
+}
diff --git a/web/src/lib/actions/team.ts b/web/src/lib/actions/team.ts
index 2feab4ead..bc3f8f228 100644
--- a/web/src/lib/actions/team.ts
+++ b/web/src/lib/actions/team.ts
@@ -202,15 +202,14 @@ export async function inviteMember(email: string, role: TeamRole) {
const token = randomBytes(32).toString('hex');
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
- // Route the invite mail through /auth/callback first so Supabase's
- // ?code= ends up at a route that calls exchangeCodeForSession() before
- // the user lands on /invite/<token>. Without this hop the invite page
- // server-renders without a session, falls into its `if (!user)` branch,
- // and ejects the user to /sign-up — where signUp() trips on the
- // existing auth.users row, no password is actually set, and the user
- // gets bounced to /sign-in with credentials that don't work.
- const inviteAcceptPath = `/invite/${token}`;
- const inviteLink = `${appUrl}/auth/callback?next=${encodeURIComponent(inviteAcceptPath)}`;
+ // What we hand to Supabase as `redirectTo`. It becomes `{{ .RedirectTo }}`
+ // in the Invite User template, which we use as the *base* for the
+ // /auth/confirm URL — token_hash + type get appended in the template.
+ // The benefit: the prefix is whatever appUrl is for *this* environment
+ // (localhost when running `pnpm dev`, app.ansvisor.com in production),
+ // independent of Supabase's project-level Site URL. So a single template
+ // works for both dev and prod.
+ const inviteLink = `${appUrl}/auth/confirm?next=${encodeURIComponent(`/invite/${token}`)}`;
const { data: invitation, error: insertError } = await supabaseAdmin
.from('invitations')