Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add landing CTA copy experiment (#2963)
Luke Vellaaeaef752082d
diff --git a/apps/landing/public/locales/en/home.json b/apps/landing/public/locales/en/home.jsonindex 82957d216..22f52e66a 100644--- a/apps/landing/public/locales/en/home.json+++ b/apps/landing/public/locales/en/home.json@@ -17,6 +17,7 @@"freeSchedulingPollMetaDescription": "Create a free scheduling poll in seconds. Ideal for organizing meetings, events, conferences, sports teams and more.","freeSchedulingPollMetaTitle": "Create a Free Scheduling Poll Instantly | No Account Required","freeSchedulingPollTitle": "Find a date for your next event",+ "getStartedForFree": "Get started for free","goodfirmsQuote": "“Unique in its simplicity and requires minimum interaction time.”","headline": "Find the best time to meet","heroDemoClose": "Close",@@ -46,7 +47,7 @@"pcmagQuote": "“Set up a scheduling poll in as little time as possible.”","popsciQuote": "“The perfect pick if you want to keep your RSVPs simple.”","statsLast30Days": "<b>{voterCount, plural, one {# person} other {# people}}</b> voted on <b>{pollCount, plural, one {# poll} other {# polls}}</b> in the last 30 days",- "subheading": "Coordinate group meetings without the back-and-forth emails",+ "subheading": "Create a poll, share the link, and let everyone vote on the times that work. It's free and nobody needs an account.","viaTrustpilot": "via Trustpilot","when2meetAlternative": "A modern When2Meet alternative","when2meetAlternativeDescription": "Rallly does everything you use When2Meet for, without the clunky parts. Create clean scheduling polls that work great on mobile, get notified when participants respond, and manage all your polls in one place. Free, without ads, and no account needed to vote. Coming from When2Meet or WhenIsGood? Rallly will feel instantly familiar.",diff --git a/apps/landing/src/app/[locale]/(main)/home-page.tsx b/apps/landing/src/app/[locale]/(main)/home-page.tsxnew file mode 100644index 000000000..c438b88d3--- /dev/null+++ b/apps/landing/src/app/[locale]/(main)/home-page.tsx@@ -0,0 +1,37 @@+import { Cta } from "@/components/home/cta";+import { CtaLabel } from "@/components/home/cta-label";+import { Hero } from "@/components/home/hero";+import { Mentions } from "@/components/home/mentions";+import { Stats } from "@/components/home/stats";+import { Testimonial } from "@/components/home/testimonial";+import { getTranslation } from "@/i18n/server";++export async function HomePage({+ locale,+ ctaVariant,+}: {+ locale: string;+ ctaVariant?: "control" | "get-started";+}) {+ const { t } = await getTranslation(locale, ["home", "common"]);+ return (+ <div className="divide-y">+ <Hero+ locale={locale}+ title={t("headline", {+ defaultValue: "Find the best time to meet",+ ns: "home",+ })}+ description={t("subheading", {+ defaultValue:+ "Create a poll, share the link, and let everyone vote on the times that work. It's free and nobody needs an account.",+ ns: "home",+ })}+ />+ <Stats locale={locale} />+ <Testimonial locale={locale} />+ <Mentions locale={locale} />+ <Cta locale={locale} callToAction={<CtaLabel variant={ctaVariant} />} />+ </div>+ );+}diff --git a/apps/landing/src/app/[locale]/(main)/landing-shell.tsx b/apps/landing/src/app/[locale]/(main)/landing-shell.tsxnew file mode 100644index 000000000..d58cc72e0--- /dev/null+++ b/apps/landing/src/app/[locale]/(main)/landing-shell.tsx@@ -0,0 +1,140 @@+import { buttonVariants } from "@rallly/ui";+import { Button } from "@rallly/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@rallly/ui/dropdown-menu";+import { Icon } from "@rallly/ui/icon";+import { MenuIcon } from "lucide-react";+import Image from "next/image";++import { Trans } from "react-i18next/TransWithoutContext";++import { CtaButton } from "@/components/home/cta-button";+import { CtaLabel } from "@/components/home/cta-label";+import { LoginButton } from "@/components/login-button";+import { LinkBase } from "@/i18n/client/link";+import { getTranslation } from "@/i18n/server";+import { linkToApp } from "@/lib/linkToApp";+import { Footer } from "./footer";+import { NavLink } from "./nav-link";++export async function LandingShell({+ locale,+ ctaVariant,+ children,+}: {+ locale: string;+ ctaVariant?: "control" | "get-started";+ children: React.ReactNode;+}) {+ const { t } = await getTranslation(locale, ["common", "home"]);+ return (+ <div className="relative z-10 flex min-h-full flex-col">+ <header className="sticky top-0 z-20 bg-gray-100">+ <div className="mx-auto flex w-full max-w-6xl items-center px-4 py-4 sm:px-6 sm:py-6">+ <div className="flex grow items-center gap-x-12">+ <LinkBase+ className="relative inline-block h-7 w-32 rounded-sm"+ href="/"+ >+ <Image+ src="/logo.svg"+ fill+ alt="rallly.co"+ className="object-contain"+ />+ </LinkBase>+ <nav className="hidden items-center gap-2 lg:flex">+ <NavLink href="https://support.rallly.co/workflow/create">+ <Trans t={t} i18nKey="howItWorks" defaults="How it works" />+ </NavLink>+ <NavLink href="/pricing">+ <Trans t={t} i18nKey="pricing" />+ </NavLink>+ <NavLink href="/blog">+ <Trans t={t} i18nKey="blog" />+ </NavLink>+ <NavLink href="https://support.rallly.co">+ <Trans t={t} i18nKey="support" />+ </NavLink>+ </nav>+ </div>+ <div className="flex items-center gap-4 sm:gap-8">+ <div className="flex items-center gap-2">+ <div className="hidden sm:block">+ <LoginButton />+ </div>+ <CtaButton size="default" captureEvent="landing:header_cta_click">+ <CtaLabel variant={ctaVariant} />+ </CtaButton>+ </div>+ <div className="flex items-center justify-center lg:hidden">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ size="sm"+ variant="ghost"+ aria-label={t("menu", { defaultValue: "Menu" })}+ />+ }+ >+ <Icon>+ <MenuIcon />+ </Icon>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ className="w-48"+ align="end"+ sideOffset={16}+ >+ <DropdownMenuItem+ render={+ <LinkBase href="https://support.rallly.co/workflow/create" />+ }+ >+ <Trans t={t} i18nKey="howItWorks" defaults="How it works" />+ </DropdownMenuItem>+ <DropdownMenuItem render={<LinkBase href="/pricing" />}>+ <Trans t={t} i18nKey="pricing" defaults="Pricing" />+ </DropdownMenuItem>+ <DropdownMenuItem render={<LinkBase href="/blog" />}>+ <Trans t={t} i18nKey="blog" />+ </DropdownMenuItem>+ <DropdownMenuItem+ render={<LinkBase href="https://support.rallly.co" />}+ >+ <Trans t={t} i18nKey="support" />+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuLabel className="space-y-2">+ <LinkBase+ href={linkToApp("/login")}+ className={buttonVariants({+ variant: "default",+ className: "w-full",+ })}+ >+ <Trans t={t} i18nKey="login" defaults="Login" />+ </LinkBase>+ </DropdownMenuLabel>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ </div>+ </header>+ <div className="mx-auto flex w-full max-w-6xl grow flex-col space-y-8 px-4 pb-4 sm:px-6 sm:pb-6">+ <section className="relative grow">{children}</section>+ <footer className="border-t pt-8 sm:pt-16">+ <Footer locale={locale} />+ </footer>+ </div>+ </div>+ );+}diff --git a/apps/landing/src/app/[locale]/(main)/layout.tsx b/apps/landing/src/app/[locale]/(main)/layout.tsxindex cb6d877ca..bef60f4c9 100644--- a/apps/landing/src/app/[locale]/(main)/layout.tsx+++ b/apps/landing/src/app/[locale]/(main)/layout.tsx@@ -1,29 +1,8 @@import languages from "@rallly/languages";-import { buttonVariants } from "@rallly/ui";-import { Button } from "@rallly/ui/button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@rallly/ui/dropdown-menu";-import { Icon } from "@rallly/ui/icon";-import { MenuIcon } from "lucide-react";import type { Viewport } from "next";import { cacheLife } from "next/cache";-import Image from "next/image";-import { Trans } from "react-i18next/TransWithoutContext";--import { CtaButton } from "@/components/home/cta-button";-import { LoginButton } from "@/components/login-button";-import { LinkBase } from "@/i18n/client/link";-import { getTranslation } from "@/i18n/server";-import { linkToApp } from "@/lib/linkToApp";-import { Footer } from "./footer";-import { NavLink } from "./nav-link";+import { LandingShell } from "./landing-shell";export async function generateStaticParams() {return Object.keys(languages).map((locale) => ({ locale }));@@ -43,114 +22,5 @@ export default async function Root(props: {const { children, params } = props;const { locale } = await params;- const { t } = await getTranslation(locale, ["common", "home"]);- return (- <div className="relative z-10 flex min-h-full flex-col">- <header className="sticky top-0 z-20 bg-gray-100">- <div className="mx-auto flex w-full max-w-6xl items-center px-4 py-4 sm:px-6 sm:py-6">- <div className="flex grow items-center gap-x-12">- <LinkBase- className="relative inline-block h-7 w-32 rounded-sm"- href="/"- >- <Image- src="/logo.svg"- fill- alt="rallly.co"- className="object-contain"- />- </LinkBase>- <nav className="hidden items-center gap-2 lg:flex">- <NavLink href="https://support.rallly.co/workflow/create">- <Trans t={t} i18nKey="howItWorks" defaults="How it works" />- </NavLink>- <NavLink href="/pricing">- <Trans t={t} i18nKey="pricing" />- </NavLink>- <NavLink href="/blog">- <Trans t={t} i18nKey="blog" />- </NavLink>- <NavLink href="https://support.rallly.co">- <Trans t={t} i18nKey="support" />- </NavLink>- </nav>- </div>- <div className="flex items-center gap-4 sm:gap-8">- <div className="flex items-center gap-2">- <div className="hidden sm:block">- <LoginButton />- </div>- <CtaButton size="default" captureEvent="landing:header_cta_click">- <Trans- t={t}- ns="home"- i18nKey="createAPoll"- defaults="Create a poll"- />- </CtaButton>- </div>- <div className="flex items-center justify-center lg:hidden">- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- size="sm"- variant="ghost"- aria-label={t("menu", { defaultValue: "Menu" })}- />- }- >- <Icon>- <MenuIcon />- </Icon>- </DropdownMenuTrigger>- <DropdownMenuContent- className="w-48"- align="end"- sideOffset={16}- >- <DropdownMenuItem- render={- <LinkBase href="https://support.rallly.co/workflow/create" />- }- >- <Trans t={t} i18nKey="howItWorks" defaults="How it works" />- </DropdownMenuItem>- <DropdownMenuItem render={<LinkBase href="/pricing" />}>- <Trans t={t} i18nKey="pricing" defaults="Pricing" />- </DropdownMenuItem>- <DropdownMenuItem render={<LinkBase href="/blog" />}>- <Trans t={t} i18nKey="blog" />- </DropdownMenuItem>- <DropdownMenuItem- render={<LinkBase href="https://support.rallly.co" />}- >- <Trans t={t} i18nKey="support" />- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuLabel className="space-y-2">- <LinkBase- href={linkToApp("/login")}- className={buttonVariants({- variant: "default",- className: "w-full",- })}- >- <Trans t={t} i18nKey="login" defaults="Login" />- </LinkBase>- </DropdownMenuLabel>- </DropdownMenuContent>- </DropdownMenu>- </div>- </div>- </div>- </header>- <div className="mx-auto flex w-full max-w-6xl grow flex-col space-y-8 px-4 pb-4 sm:px-6 sm:pb-6">- <section className="relative grow">{children}</section>- <footer className="border-t pt-8 sm:pt-16">- <Footer locale={locale} />- </footer>- </div>- </div>- );+ return <LandingShell locale={locale}>{children}</LandingShell>;}diff --git a/apps/landing/src/app/[locale]/(main)/page.tsx b/apps/landing/src/app/[locale]/(main)/page.tsxindex 4eab8fb53..f357add2c 100644--- a/apps/landing/src/app/[locale]/(main)/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/page.tsx@@ -2,39 +2,15 @@import type { Metadata } from "next";import { cacheLife } from "next/cache";-import { Cta } from "@/components/home/cta";-import { Hero } from "@/components/home/hero";-import { Mentions } from "@/components/home/mentions";-import { Stats } from "@/components/home/stats";-import { Testimonial } from "@/components/home/testimonial";import { getTranslation } from "@/i18n/server";+import { HomePage } from "./home-page";export default async function Page(props: {params: Promise<{ locale: string }>;}) {cacheLife("days");const { locale } = await props.params;- const { t } = await getTranslation(locale, ["home", "common"]);- return (- <div className="divide-y">- <Hero- locale={locale}- title={t("headline", {- defaultValue: "Find the best time to meet",- ns: "home",- })}- description={t("subheading", {- defaultValue:- "Coordinate group meetings without the back-and-forth emails",- ns: "home",- })}- />- <Stats locale={locale} />- <Testimonial locale={locale} />- <Mentions locale={locale} />- <Cta locale={locale} />- </div>- );+ return <HomePage locale={locale} />;}export async function generateMetadata(props: {diff --git a/apps/landing/src/app/[locale]/exp/landing-cta-get-started/layout.tsx b/apps/landing/src/app/[locale]/exp/landing-cta-get-started/layout.tsxnew file mode 100644index 000000000..fae60cff5--- /dev/null+++ b/apps/landing/src/app/[locale]/exp/landing-cta-get-started/layout.tsx@@ -0,0 +1,30 @@+import languages from "@rallly/languages";+import type { Viewport } from "next";+import { cacheLife } from "next/cache";++import { LandingShell } from "../../(main)/landing-shell";++export async function generateStaticParams() {+ return Object.keys(languages).map((locale) => ({ locale }));+}++export const viewport: Viewport = {+ width: "device-width",+ initialScale: 1,+};++export default async function Root(props: {+ children: React.ReactNode;+ params: Promise<{ locale: string }>;+}) {+ "use cache";+ cacheLife("max");+ const { children, params } = props;+ const { locale } = await params;++ return (+ <LandingShell locale={locale} ctaVariant="get-started">+ {children}+ </LandingShell>+ );+}diff --git a/apps/landing/src/app/[locale]/exp/landing-cta-get-started/page.tsx b/apps/landing/src/app/[locale]/exp/landing-cta-get-started/page.tsxnew file mode 100644index 000000000..87ce9688f--- /dev/null+++ b/apps/landing/src/app/[locale]/exp/landing-cta-get-started/page.tsx@@ -0,0 +1,37 @@+"use cache";++import type { Metadata } from "next";+import { cacheLife } from "next/cache";+import { getTranslation } from "@/i18n/server";+import { HomePage } from "../../(main)/home-page";++// The get-started variant of the home page. Only reached via the middleware+// rewrite in lib/cta-experiment.ts — the visitor's URL stays "/".++export default async function Page(props: {+ params: Promise<{ locale: string }>;+}) {+ cacheLife("days");+ const { locale } = await props.params;+ return <HomePage locale={locale} ctaVariant="get-started" />;+}++export async function generateMetadata(props: {+ params: Promise<{ locale: string }>;+}): Promise<Metadata> {+ cacheLife("max");+ const { locale } = await props.params;+ const { t } = await getTranslation(locale, "home");+ return {+ title: t("metaTitle", {+ defaultValue: "Rallly: Free Group Meeting Scheduling Tool",+ ns: "home",+ }),+ description: t("metaDescription", {+ ns: "home",+ defaultValue:+ "Rallly is the fastest and easiest scheduling and collaboration tool. Create a meeting poll in seconds, no login required.",+ }),+ robots: { index: false, follow: false },+ };+}diff --git a/apps/landing/src/components/home/cta-label.tsx b/apps/landing/src/components/home/cta-label.tsxnew file mode 100644index 000000000..df79c3032--- /dev/null+++ b/apps/landing/src/components/home/cta-label.tsx@@ -0,0 +1,24 @@+"use client";+import { useFeatureFlagVariantKey } from "@rallly/posthog/client";+import React from "react";+import { Trans } from "@/i18n/client/trans";++export function CtaLabel({ variant }: { variant?: "control" | "get-started" }) {+ const flagVariant = useFeatureFlagVariantKey("landing-cta-copy");+ // Without a server-assigned variant the static HTML says control, so the+ // flag value (which may be bootstrapped from a cookie and available on the+ // first client render) must not apply until after hydration.+ const [mounted, setMounted] = React.useState(false);+ React.useEffect(() => setMounted(true), []);+ const resolved = variant ?? (mounted ? flagVariant : undefined);+ if (resolved === "get-started") {+ return (+ <Trans+ ns="home"+ i18nKey="getStartedForFree"+ defaults="Get started for free"+ />+ );+ }+ return <Trans ns="home" i18nKey="createAPoll" defaults="Create a poll" />;+}diff --git a/apps/landing/src/components/home/cta.tsx b/apps/landing/src/components/home/cta.tsxindex 06167567d..1711cf7f5 100644--- a/apps/landing/src/components/home/cta.tsx+++ b/apps/landing/src/components/home/cta.tsx@@ -2,6 +2,7 @@ import { cn } from "@rallly/ui";import type * as React from "react";import { Trans } from "react-i18next/TransWithoutContext";import { CtaButton } from "@/components/home/cta-button";+import { CtaLabel } from "@/components/home/cta-label";import { FadeIn } from "@/components/home/fade-in";import { handwritten } from "@/fonts/handwritten";import { getTranslation } from "@/i18n/server";@@ -45,14 +46,7 @@ export async function Cta({</div><div className="mt-6 flex flex-col items-start gap-4"><CtaButton captureEvent="landing:final_cta_click">- {callToAction ?? (- <Trans- t={t}- ns="home"- i18nKey="createAPoll"- defaults="Create a poll"- />- )}+ {callToAction ?? <CtaLabel />}</CtaButton><pclassName={cn(diff --git a/apps/landing/src/lib/cta-experiment.ts b/apps/landing/src/lib/cta-experiment.tsnew file mode 100644index 000000000..05e42bd66--- /dev/null+++ b/apps/landing/src/lib/cta-experiment.ts@@ -0,0 +1,142 @@+import { getPreferredLocale } from "@rallly/languages/get-preferred-locale";+import type { NextRequest } from "next/server";+import { fallbackLng, languages } from "@/i18n/settings";++// Edge bucketing for the landing CTA copy experiment. The home page is+// statically cached, so the variant is decided here and served by rewriting+// to a second statically generated route — the visitor's URL stays "/".+//+// PostHog stays the control plane: the variant comes from its /flags endpoint+// (a deterministic hash of the distinct id, so assignment is sticky by+// itself), and the ph_ff_* cookie is only a latency cache. While the+// experiment is a draft or after it stops, /flags returns no variant and+// everyone gets control with no deploy needed. The client bootstraps+// posthog-js from the same cookies (see @rallly/posthog/client), so exposure+// events report the variant the visitor actually saw.++const EXPERIMENT_FLAG = "landing-cta-copy";+const REWRITE_VARIANT = "get-started";+const FLAG_COOKIE = `ph_ff_${EXPERIMENT_FLAG}`;+const DISTINCT_ID_COOKIE = "ph_did";+const FLAG_COOKIE_MAX_AGE = 60 * 60;+const DISTINCT_ID_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;+const FLAGS_REQUEST_TIMEOUT_MS = 300;++const BOT_PATTERN =+ /bot|crawl|spider|slurp|bingpreview|facebookexternalhit|whatsapp|telegram|vercel-screenshot|lighthouse/i;++type CookieToSet = { name: string; value: string; maxAge: number };++export type ExperimentDecision = {+ locale: string;+ variant: string;+ cookies: CookieToSet[];+};++function getHomeLocale(req: NextRequest): string | null {+ const { pathname } = req.nextUrl;+ if (pathname === "/") {+ // A non-default preferred locale gets redirected by the i18n middleware+ // first; the experiment applies on the follow-up localized request.+ const preferredLocale = getPreferredLocale({+ acceptLanguageHeader: req.headers.get("accept-language") ?? undefined,+ });+ return preferredLocale === fallbackLng ? fallbackLng : null;+ }+ const locale = languages.find((lng) => pathname === `/${lng}`);+ // "/en" redirects to "/" in the i18n middleware; skip it here.+ return locale && locale !== fallbackLng ? locale : null;+}++function readPosthogDistinctId(req: NextRequest): string | undefined {+ for (const cookie of req.cookies.getAll()) {+ if (cookie.name.startsWith("ph_") && cookie.name.endsWith("_posthog")) {+ try {+ const parsed = JSON.parse(decodeURIComponent(cookie.value));+ if (typeof parsed.distinct_id === "string") {+ return parsed.distinct_id;+ }+ } catch {+ // fall through to the ph_did cookie or a fresh id+ }+ }+ }+ return undefined;+}++async function fetchVariant(distinctId: string): Promise<string | null> {+ const host = process.env.NEXT_PUBLIC_POSTHOG_API_HOST;+ const apiKey = process.env.NEXT_PUBLIC_POSTHOG_API_KEY;+ if (!host || !apiKey) {+ return null;+ }+ try {+ const res = await fetch(`${host}/flags/?v=2`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ api_key: apiKey, distinct_id: distinctId }),+ signal: AbortSignal.timeout(FLAGS_REQUEST_TIMEOUT_MS),+ });+ if (!res.ok) {+ return null;+ }+ const data = await res.json();+ const value =+ data?.flags?.[EXPERIMENT_FLAG]?.variant ??+ data?.featureFlags?.[EXPERIMENT_FLAG];+ return typeof value === "string" ? value : "control";+ } catch {+ return null;+ }+}++export async function getCtaExperimentDecision(+ req: NextRequest,+): Promise<ExperimentDecision | null> {+ const locale = getHomeLocale(req);+ if (!locale) {+ return null;+ }+ if (BOT_PATTERN.test(req.headers.get("user-agent") ?? "")) {+ return null;+ }++ const cached = req.cookies.get(FLAG_COOKIE)?.value;+ if (cached) {+ return { locale, variant: cached, cookies: [] };+ }++ const cookies: CookieToSet[] = [];+ let distinctId =+ readPosthogDistinctId(req) ?? req.cookies.get(DISTINCT_ID_COOKIE)?.value;+ if (!distinctId) {+ distinctId = crypto.randomUUID();+ cookies.push({+ name: DISTINCT_ID_COOKIE,+ value: distinctId,+ maxAge: DISTINCT_ID_COOKIE_MAX_AGE,+ });+ }++ const variant = await fetchVariant(distinctId);+ if (variant === null) {+ // PostHog was unreachable: serve control without caching the miss so the+ // next request retries with the same distinct id.+ return { locale, variant: "control", cookies };+ }+ cookies.push({+ name: FLAG_COOKIE,+ value: variant,+ maxAge: FLAG_COOKIE_MAX_AGE,+ });+ return { locale, variant, cookies };+}++export function getVariantRewritePath(+ decision: ExperimentDecision,+): string | null {+ if (decision.variant !== REWRITE_VARIANT) {+ return null;+ }+ return `/${decision.locale}/exp/landing-cta-${REWRITE_VARIANT}`;+}diff --git a/apps/landing/src/proxy.ts b/apps/landing/src/proxy.tsindex 4ca1310b8..e5e965218 100644--- a/apps/landing/src/proxy.ts+++ b/apps/landing/src/proxy.ts@@ -1,8 +1,36 @@import type { NextRequest } from "next/server";+import { NextResponse } from "next/server";import { i18nMiddleware } from "@/i18n/middleware";+import { headerName } from "@/i18n/settings";+import {+ getCtaExperimentDecision,+ getVariantRewritePath,+} from "@/lib/cta-experiment";export async function proxy(req: NextRequest) {- return i18nMiddleware(req);+ const decision = await getCtaExperimentDecision(req);+ const rewritePath = decision && getVariantRewritePath(decision);++ let res: NextResponse;+ if (decision && rewritePath) {+ const url = req.nextUrl.clone();+ url.pathname = rewritePath;+ const headers = new Headers(req.headers);+ headers.set(headerName, decision.locale);+ res = NextResponse.rewrite(url, { request: { headers } });+ } else {+ res = i18nMiddleware(req);+ }++ for (const cookie of decision?.cookies ?? []) {+ res.cookies.set(cookie.name, cookie.value, {+ maxAge: cookie.maxAge,+ path: "/",+ sameSite: "lax",+ secure: process.env.NODE_ENV === "production",+ });+ }+ return res;}export const config = {diff --git a/packages/posthog/src/client.ts b/packages/posthog/src/client.tsindex 925f4773e..3cf0074c7 100644--- a/packages/posthog/src/client.ts+++ b/packages/posthog/src/client.ts@@ -1,15 +1,49 @@"use client";import posthog from "posthog-js";-export { useFeatureFlagEnabled } from "posthog-js/react";+export {+ useFeatureFlagEnabled,+ useFeatureFlagVariantKey,+} from "posthog-js/react";import {isGlobalPrivacyControlEnabled,isInjectedExtensionException,} from "./utils";+// Edge middleware can pre-assign feature flags (one `ph_ff_<flag>` cookie per+// flag, plus `ph_did` for the distinct id it evaluated them against) so the+// first client render agrees with the server-rendered variant. The distinct id+// is only adopted while PostHog has no identity of its own; stored identities+// take precedence.+function getBootstrapData() {+ const featureFlags: Record<string, string> = {};+ let distinctID: string | undefined;+ let hasOwnIdentity = false;+ for (const cookie of document.cookie.split("; ")) {+ const separatorIndex = cookie.indexOf("=");+ const name = cookie.slice(0, separatorIndex);+ const value = cookie.slice(separatorIndex + 1);+ if (name.startsWith("ph_ff_")) {+ featureFlags[name.slice("ph_ff_".length)] = value;+ } else if (name === "ph_did") {+ distinctID = value;+ } else if (name.startsWith("ph_") && name.endsWith("_posthog")) {+ hasOwnIdentity = true;+ }+ }+ if (Object.keys(featureFlags).length === 0 && !distinctID) {+ return undefined;+ }+ return {+ distinctID: hasOwnIdentity ? undefined : distinctID,+ featureFlags,+ };+}+if (typeof window !== "undefined" && process.env.NEXT_PUBLIC_POSTHOG_API_KEY) {posthog.init(process.env.NEXT_PUBLIC_POSTHOG_API_KEY, {+ bootstrap: getBootstrapData(),debug: false,api_host: process.env.NEXT_PUBLIC_POSTHOG_API_HOST,ui_host: process.env.NEXT_PUBLIC_POSTHOG_UI_HOST,