Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Add NEXT_PUBLIC_COOKIE_DOMAIN for cross-subdomain cookies (#2374)

Luke Vella43af5a9e1ea7
diff --git a/apps/web/src/auth/plugins/host-only-cookie-cleanup.ts b/apps/web/src/auth/plugins/host-only-cookie-cleanup.ts
new file mode 100644
index 000000000..ee32112a6
--- /dev/null
+++ b/apps/web/src/auth/plugins/host-only-cookie-cleanup.ts
@@ -0,0 +1,45 @@
+import type { BetterAuthPlugin } from "better-auth";
+import { createAuthMiddleware } from "better-auth/api";
+import { parseSetCookieHeader } from "better-auth/cookies";
+import { env } from "@/env";
+
+// Paths where better-auth either mints a new session cookie or clears the
+// existing one. The cleanup only runs on these.
+// Deletes the host-only variants of better-auth's session cookies left over
+// from before cross-subdomain mode was enabled. Must be registered *after*
+// the anonymous plugin so its after-hook runs second — the anonymous plugin
+// detects new sessions by parsing Set-Cookie into a name-keyed map, and
+// running our deletion last keeps that lookup pointing at the real session
+// token rather than our empty placeholder.
+export const hostOnlyCookieCleanup: BetterAuthPlugin = {
+ id: "host-only-cookie-cleanup",
+ hooks: {
+ after: [
+ {
+ matcher: () => !!env.NEXT_PUBLIC_COOKIE_DOMAIN,
+ handler: createAuthMiddleware(async (ctx) => {
+ // /sign-out always cleans up. For every other path, only clean
+ // up when a real session token actually landed in the response
+ // — covers sign-in, sign-up, OAuth callbacks, OTP verify, and
+ // periodic session refresh, while skipping failed logins, OTP
+ // sends, redirect-only endpoints, and plain session reads.
+ if (ctx.path !== "/sign-out") {
+ const setCookie = ctx.context.responseHeaders?.get("set-cookie");
+ const sessionTokenName = ctx.context.authCookies.sessionToken.name;
+ const newToken = parseSetCookieHeader(setCookie ?? "")
+ .get(sessionTokenName)
+ ?.value.split(".")[0];
+ if (!newToken) return;
+ }
+ for (const cookie of [
+ ctx.context.authCookies.sessionToken,
+ ctx.context.authCookies.sessionData,
+ ]) {
+ const { domain: _, ...attributes } = cookie.attributes;
+ ctx.setCookie(cookie.name, "", { ...attributes, maxAge: 0 });
+ }
+ }),
+ },
+ ],
+ },
+};
diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts
index e5b16c6c8..f97b0eb81 100644
--- a/apps/web/src/env.ts
+++ b/apps/web/src/env.ts
@@ -181,6 +181,19 @@ export const env = createEnv({
* If not set, assets are proxied through Next.js (current behaviour).
*/
NEXT_PUBLIC_CDN_BASE_URL: z.url().optional(),
+ /**
+ * Domain to attach to server-set cookies (auth session, locale).
+ * Set to a parent domain prefixed with a leading dot (e.g. `.rallly.co`)
+ * to make these cookies readable across subdomains. When unset, cookies
+ * stay scoped to the apex host of the request.
+ */
+ NEXT_PUBLIC_COOKIE_DOMAIN: z
+ .string()
+ .regex(/^\.?[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*$/, {
+ message:
+ "must be a hostname or optional leading-dot domain (no protocol/port/path)",
+ })
+ .optional(),
},
/*
* Due to how Next.js bundles environment variables on Edge and Client,
@@ -253,6 +266,7 @@ export const env = createEnv({
API_BASE_URL: process.env.API_BASE_URL,
NEXT_PUBLIC_TURNSTILE_SITE_KEY: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY,
NEXT_PUBLIC_CDN_BASE_URL: process.env.NEXT_PUBLIC_CDN_BASE_URL,
+ NEXT_PUBLIC_COOKIE_DOMAIN: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
},
skipValidation: !!process.env.SKIP_ENV_VALIDATION,
});
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
index c21d51df1..98a51f0b8 100644
--- a/apps/web/src/lib/auth.ts
+++ b/apps/web/src/lib/auth.ts
@@ -20,6 +20,7 @@ import { cache } from "react";
import { isEmailBlocked } from "@/auth/helpers/is-email-blocked";
import { linkAnonymousUser } from "@/auth/helpers/merge-user";
import { isTemporaryEmail } from "@/auth/helpers/temp-email-domains";
+import { hostOnlyCookieCleanup } from "@/auth/plugins/host-only-cookie-cleanup";
import { env } from "@/env";
import { posthog } from "@/features/analytics/posthog";
import { createSpace } from "@/features/space/mutations";
@@ -178,6 +179,7 @@ export const authLib = betterAuth({
},
}),
...conditionalPlugins,
+ hostOnlyCookieCleanup,
],
socialProviders: {
google:
@@ -356,6 +358,14 @@ export const authLib = betterAuth({
maxAge: 5 * 60, // 5 minutes
},
},
+ advanced: env.NEXT_PUBLIC_COOKIE_DOMAIN
+ ? {
+ crossSubDomainCookies: {
+ enabled: true,
+ domain: env.NEXT_PUBLIC_COOKIE_DOMAIN,
+ },
+ }
+ : undefined,
trustedOrigins: [absoluteUrl()],
baseURL,
});
diff --git a/apps/web/src/lib/locale/client.tsx b/apps/web/src/lib/locale/client.tsx
index ed90a4dc9..6d8783ce2 100644
--- a/apps/web/src/lib/locale/client.tsx
+++ b/apps/web/src/lib/locale/client.tsx
@@ -3,6 +3,7 @@ import { toast } from "@rallly/ui/sonner";
import Cookies from "js-cookie";
import { useParams, useRouter } from "next/navigation";
import React from "react";
+import { env } from "@/env";
import { useTranslation } from "@/i18n/client";
import { LOCALE_COOKIE_NAME } from "@/lib/locale/constants";
@@ -35,7 +36,10 @@ export function LocaleSync({ userLocale }: { userLocale?: string }) {
}
export function setLocaleCookie(locale: string) {
- Cookies.set(LOCALE_COOKIE_NAME, locale, { path: "/" });
+ Cookies.set(LOCALE_COOKIE_NAME, locale, {
+ path: "/",
+ domain: env.NEXT_PUBLIC_COOKIE_DOMAIN,
+ });
}
export function useLocale() {
diff --git a/apps/web/src/lib/locale/server.ts b/apps/web/src/lib/locale/server.ts
index 4f6c57455..90f9b287a 100644
--- a/apps/web/src/lib/locale/server.ts
+++ b/apps/web/src/lib/locale/server.ts
@@ -3,6 +3,11 @@ import { getPreferredLocaleFromHeaders } from "@rallly/languages/get-preferred-l
import type { NextRequest, NextResponse } from "next/server";
import { LOCALE_COOKIE_NAME } from "@/lib/locale/constants";
+// Read via process.env to keep `@/env` out of the middleware bundle —
+// t3-env validates eagerly on import and would crash server boot on any
+// misconfigured server var. Shape is still validated in `@/env`.
+const cookieDomain = process.env.NEXT_PUBLIC_COOKIE_DOMAIN;
+
export function getLocaleFromRequest(req: NextRequest) {
const localeCookie = req.cookies.get(LOCALE_COOKIE_NAME);
if (localeCookie && supportedLngs.includes(localeCookie.value)) {
@@ -21,15 +26,12 @@ export function getLocaleFromRequest(req: NextRequest) {
}
export function setLocaleCookie(
- req: NextRequest,
+ _req: NextRequest,
res: NextResponse,
locale: string,
) {
- if (req.cookies.get(LOCALE_COOKIE_NAME)) {
- return;
- }
-
res.cookies.set(LOCALE_COOKIE_NAME, locale, {
path: "/",
+ domain: cookieDomain,
});
}