Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(web): add sentinel redirect for /project/~/[...path] (#14326)

Mark Salpeter2551133ebc9e
diff --git a/web/src/__tests__/server/unit/projectSentinelRedirect.servertest.ts b/web/src/__tests__/server/unit/projectSentinelRedirect.servertest.ts
new file mode 100644
index 0000000000..71121a7ddd
--- /dev/null
+++ b/web/src/__tests__/server/unit/projectSentinelRedirect.servertest.ts
@@ -0,0 +1,330 @@
+const mockEnv = vi.hoisted(() => ({
+ env: {
+ NEXTAUTH_URL: "https://us.cloud.langfuse.com",
+ NEXTAUTH_COOKIE_DOMAIN: "langfuse.com",
+ NEXT_PUBLIC_BASE_PATH: "",
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "US",
+ VERCEL: undefined as string | undefined,
+ },
+}));
+
+vi.mock("@/src/env.mjs", () => mockEnv);
+
+const { getServerAuthSessionMock } = vi.hoisted(() => ({
+ getServerAuthSessionMock: vi.fn(),
+}));
+
+vi.mock("@/src/server/auth", () => ({
+ getServerAuthSession: getServerAuthSessionMock,
+}));
+
+import {
+ projectCookieName,
+ type ProjectCookie,
+} from "@/src/server/utils/cookies";
+import { getServerSideProps } from "@/src/pages/project/~/[[...path]]";
+import { type GetServerSidePropsContext } from "next";
+
+const makeCtx = (
+ params?: Record<string, string | string[]>,
+ resolvedUrl?: string,
+ req: {
+ host?: string;
+ proto?: string;
+ cookie?: ProjectCookie;
+ } = {},
+): GetServerSidePropsContext => {
+ const path = (params?.path as string[] | undefined) ?? [];
+ const url =
+ resolvedUrl ??
+ `/project/~${path.length ? `/${path.map(encodeURIComponent).join("/")}` : ""}`;
+ return {
+ req: {
+ headers: {
+ host: req.host ?? "us.cloud.langfuse.com",
+ "x-forwarded-proto": req.proto ?? "https",
+ },
+ cookies: req.cookie
+ ? { [projectCookieName]: JSON.stringify(req.cookie) }
+ : {},
+ },
+ res: {},
+ resolvedUrl: url,
+ } as unknown as GetServerSidePropsContext;
+};
+
+const makeSession = (projectIds: string[]) => ({
+ user: {
+ organizations: [
+ {
+ id: "org-1",
+ projects: projectIds.map((id) => ({ id })),
+ },
+ ],
+ },
+});
+
+describe("sentinel redirect /project/~/", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("unauthenticated: redirects to sign-in with callbackUrl", async () => {
+ getServerAuthSessionMock.mockResolvedValue(null);
+
+ const result = await getServerSideProps(
+ makeCtx(undefined, "/project/~/traces"),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: `/auth/sign-in?callbackUrl=${encodeURIComponent("/project/~/traces")}`,
+ permanent: false,
+ },
+ });
+ });
+
+ it("no accessible projects: redirects to /", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession([]));
+
+ const result = await getServerSideProps(makeCtx());
+
+ expect(result).toEqual({
+ redirect: { destination: "/", permanent: false },
+ });
+ });
+
+ it("first project, no sub-path: redirects to /project/{id}", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+
+ const result = await getServerSideProps(makeCtx());
+
+ expect(result).toEqual({
+ redirect: { destination: "/project/proj-abc", permanent: false },
+ });
+ });
+
+ it("single path segment: rewrites correctly", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+
+ const result = await getServerSideProps(makeCtx({ path: ["traces"] }));
+
+ expect(result).toEqual({
+ redirect: { destination: "/project/proj-abc/traces", permanent: false },
+ });
+ });
+
+ it("nested path: rewrites all segments", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces", "trace-123"] }),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "/project/proj-abc/traces/trace-123",
+ permanent: false,
+ },
+ });
+ });
+
+ it("deeply nested path: rewrites all segments", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["settings", "models", "model-456"] }),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "/project/proj-abc/settings/models/model-456",
+ permanent: false,
+ },
+ });
+ });
+
+ it("multiple accessible projects: uses the first", async () => {
+ getServerAuthSessionMock.mockResolvedValue(
+ makeSession(["proj-first", "proj-second"]),
+ );
+
+ const result = await getServerSideProps(makeCtx({ path: ["traces"] }));
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "/project/proj-first/traces",
+ permanent: false,
+ },
+ });
+ });
+
+ it("path segment with reserved chars: encodes each segment", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["prompts", "What is X?"] }),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "/project/proj-abc/prompts/What%20is%20X%3F",
+ permanent: false,
+ },
+ });
+ });
+
+ it("same-origin cookie, member project: redirects to cookie project", async () => {
+ getServerAuthSessionMock.mockResolvedValue(
+ makeSession(["proj-first", "proj-last"]),
+ );
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces"] }, "/project/~/traces", {
+ host: "us.cloud.langfuse.com",
+ cookie: {
+ origin: "https://us.cloud.langfuse.com",
+ projectId: "proj-last",
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ redirect: { destination: "/project/proj-last/traces", permanent: false },
+ });
+ });
+
+ it("same-origin cookie, non-member project: falls back to first project", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-first"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces"] }, "/project/~/traces", {
+ host: "us.cloud.langfuse.com",
+ cookie: {
+ origin: "https://us.cloud.langfuse.com",
+ projectId: "proj-gone",
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ redirect: { destination: "/project/proj-first/traces", permanent: false },
+ });
+ });
+
+ it("cross-region cookie, same parent domain: bounces to cookie origin sentinel", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-first"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces"] }, "/project/~/traces", {
+ host: "us.cloud.langfuse.com",
+ cookie: {
+ origin: "https://eu.cloud.langfuse.com",
+ projectId: "proj-eu",
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "https://eu.cloud.langfuse.com/project/~/traces",
+ permanent: false,
+ },
+ });
+ });
+
+ it("unauthenticated cross-region cookie: bounces to cookie origin before sign-in", async () => {
+ getServerAuthSessionMock.mockResolvedValue(null);
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces"] }, "/project/~/traces", {
+ host: "us.cloud.langfuse.com",
+ cookie: {
+ origin: "https://eu.cloud.langfuse.com",
+ projectId: "proj-eu",
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "https://eu.cloud.langfuse.com/project/~/traces",
+ permanent: false,
+ },
+ });
+ expect(getServerAuthSessionMock).not.toHaveBeenCalled();
+ });
+
+ it("cross-origin cookie, different parent domain: falls back to first project", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-first"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces"] }, "/project/~/traces", {
+ host: "us.cloud.langfuse.com",
+ cookie: {
+ origin: "https://evil.example.com",
+ projectId: "proj-evil",
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ redirect: { destination: "/project/proj-first/traces", permanent: false },
+ });
+ });
+
+ it("same-origin cookie: preserves query string on local redirect", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-last"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces"] }, "/project/~/traces?foo=bar&baz=1", {
+ host: "us.cloud.langfuse.com",
+ cookie: {
+ origin: "https://us.cloud.langfuse.com",
+ projectId: "proj-last",
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "/project/proj-last/traces?foo=bar&baz=1",
+ permanent: false,
+ },
+ });
+ });
+
+ it("cross-region bounce: preserves query string on cross-host redirect", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-first"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces"] }, "/project/~/traces?foo=bar", {
+ host: "us.cloud.langfuse.com",
+ cookie: {
+ origin: "https://eu.cloud.langfuse.com",
+ projectId: "proj-eu",
+ },
+ }),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "https://eu.cloud.langfuse.com/project/~/traces?foo=bar",
+ permanent: false,
+ },
+ });
+ });
+
+ it("first-project fallback: preserves query string", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-first"]));
+
+ const result = await getServerSideProps(
+ makeCtx({ path: ["traces"] }, "/project/~/traces?foo=bar"),
+ );
+
+ expect(result).toEqual({
+ redirect: {
+ destination: "/project/proj-first/traces?foo=bar",
+ permanent: false,
+ },
+ });
+ });
+});
diff --git a/web/src/__tests__/server/unit/projectVisitRoute.servertest.ts b/web/src/__tests__/server/unit/projectVisitRoute.servertest.ts
new file mode 100644
index 0000000000..2e8c274177
--- /dev/null
+++ b/web/src/__tests__/server/unit/projectVisitRoute.servertest.ts
@@ -0,0 +1,135 @@
+const mockEnv = vi.hoisted(() => ({
+ env: {
+ NEXTAUTH_URL: "https://us.cloud.langfuse.com",
+ NEXTAUTH_COOKIE_DOMAIN: "langfuse.com",
+ NEXT_PUBLIC_BASE_PATH: "",
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "US",
+ VERCEL: undefined as string | undefined,
+ },
+}));
+
+vi.mock("@/src/env.mjs", () => mockEnv);
+
+const { getServerAuthSessionMock } = vi.hoisted(() => ({
+ getServerAuthSessionMock: vi.fn(),
+}));
+
+vi.mock("@/src/server/auth", () => ({
+ getServerAuthSession: getServerAuthSessionMock,
+}));
+
+import handler from "@/src/pages/api/project/[projectId]/visit";
+import { type NextApiRequest, type NextApiResponse } from "next";
+
+const makeSession = (projectIds: string[]) => ({
+ user: {
+ organizations: [
+ { id: "org-1", projects: projectIds.map((id) => ({ id })) },
+ ],
+ },
+});
+
+const makeReqRes = (opts: {
+ method?: string;
+ query?: Record<string, string | string[]>;
+ headers?: Record<string, string>;
+}) => {
+ const setHeader = vi.fn();
+ const json = vi.fn();
+ const end = vi.fn();
+ const status = vi.fn().mockReturnValue({ json, end });
+ const req = {
+ method: opts.method ?? "POST",
+ query: opts.query ?? {},
+ headers: opts.headers ?? { host: "us.cloud.langfuse.com" },
+ } as unknown as NextApiRequest;
+ const res = { setHeader, status } as unknown as NextApiResponse;
+ return { req, res, setHeader, status, json, end };
+};
+
+describe("POST /api/project/visit", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("non-POST method: returns 405 without setting a cookie", async () => {
+ const { req, res, status, setHeader } = makeReqRes({ method: "GET" });
+
+ await handler(req, res);
+
+ expect(status).toHaveBeenCalledWith(405);
+ expect(setHeader).not.toHaveBeenCalled();
+ });
+
+ it("unauthenticated: returns 401 without setting a cookie", async () => {
+ getServerAuthSessionMock.mockResolvedValue(null);
+ const { req, res, status, setHeader } = makeReqRes({
+ query: { projectId: "proj-abc" },
+ });
+
+ await handler(req, res);
+
+ expect(status).toHaveBeenCalledWith(401);
+ expect(setHeader).not.toHaveBeenCalled();
+ });
+
+ it("member project: sets cookie with server-derived origin", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+ const { req, res, status, setHeader } = makeReqRes({
+ query: { projectId: "proj-abc" },
+ headers: {
+ host: "us.cloud.langfuse.com",
+ "x-forwarded-proto": "https",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(status).toHaveBeenCalledWith(204);
+ expect(setHeader).toHaveBeenCalledTimes(1);
+ const [header, value] = setHeader.mock.calls[0];
+ expect(header).toBe("Set-Cookie");
+ expect(value).toContain("langfuse.project=");
+ const cookieJson = JSON.parse(
+ decodeURIComponent((value as string).split("=")[1].split(";")[0]),
+ );
+ expect(cookieJson).toEqual({
+ origin: "https://us.cloud.langfuse.com",
+ projectId: "proj-abc",
+ });
+ expect(value).toContain("Domain=langfuse.com");
+ expect(value).toContain("HttpOnly");
+ });
+
+ it("non-member project: no-op (no cookie), returns 204", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+ const { req, res, status, setHeader } = makeReqRes({
+ query: { projectId: "proj-other" },
+ });
+
+ await handler(req, res);
+
+ expect(status).toHaveBeenCalledWith(204);
+ expect(setHeader).not.toHaveBeenCalled();
+ });
+
+ it("missing project id: returns 400", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+ const { req, res, status, setHeader } = makeReqRes({ query: {} });
+
+ await handler(req, res);
+
+ expect(status).toHaveBeenCalledWith(400);
+ expect(setHeader).not.toHaveBeenCalled();
+ });
+
+ it("array project id: returns 400", async () => {
+ getServerAuthSessionMock.mockResolvedValue(makeSession(["proj-abc"]));
+ const { req, res, status, setHeader } = makeReqRes({
+ query: { projectId: ["proj-abc", "proj-xyz"] },
+ });
+
+ await handler(req, res);
+
+ expect(status).toHaveBeenCalledWith(400);
+ expect(setHeader).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
index 74c1b3d02d..30d74a64c2 100644
--- a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
+++ b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx
@@ -4,8 +4,9 @@
* Used for all main application pages when user is authenticated
*/
-import { useState, type PropsWithChildren } from "react";
+import { useEffect, useState, type PropsWithChildren } from "react";
import Head from "next/head";
+import { useRouter, type NextRouter } from "next/router";
import { SidebarProvider, SidebarInset } from "@/src/components/ui/sidebar";
import { AppSidebar } from "@/src/components/nav/app-sidebar";
import { Toaster } from "@/src/components/ui/sonner";
@@ -104,6 +105,8 @@ export function AuthenticatedLayout({
}: AuthenticatedLayoutProps) {
const { isLangfuseCloud, region: currentRegion } = useLangfuseCloudRegion();
const [featurePreviewOpen, setFeaturePreviewOpen] = useState(false);
+ const router = useRouter();
+ useProjectCookie(router);
// Safe assertion: AuthenticatedLayout is only rendered after auth checks pass
// in AppLayout, which guarantees session.user exists at this point
@@ -215,3 +218,14 @@ export function AuthenticatedLayout({
</>
);
}
+
+/** useProjectCookie pings the visit beacon so the project sentinel can route the user back here. */
+function useProjectCookie(router: NextRouter) {
+ const projectId = router.query.projectId;
+ useEffect(() => {
+ if (typeof projectId !== "string") return;
+ fetch(`/api/project/${encodeURIComponent(projectId)}/visit`, {
+ method: "POST",
+ }).catch(() => {});
+ }, [projectId]);
+}
diff --git a/web/src/pages/api/project/[projectId]/visit.ts b/web/src/pages/api/project/[projectId]/visit.ts
new file mode 100644
index 0000000000..273cd5f423
--- /dev/null
+++ b/web/src/pages/api/project/[projectId]/visit.ts
@@ -0,0 +1,38 @@
+import { type NextApiRequest, type NextApiResponse } from "next";
+
+import { getServerAuthSession } from "@/src/server/auth";
+import {
+ getRequestOrigin,
+ serializeProjectCookie,
+} from "@/src/server/utils/cookies";
+
+/** handler persists the user's current project in the region-unscoped project cookie. */
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST")
+ return res.status(405).json({ message: "Method not allowed" });
+
+ const session = await getServerAuthSession({ req, res });
+ if (!session?.user) {
+ return res.status(401).json({ message: "Unauthorized" });
+ }
+
+ const projectId = req.query.projectId;
+ if (typeof projectId !== "string" || projectId.length === 0) {
+ return res.status(400).json({ message: "Invalid project id" });
+ }
+
+ const isMember = session.user.organizations
+ .flatMap((org) => org.projects)
+ .some((project) => project.id === projectId);
+
+ const origin = getRequestOrigin(req);
+
+ if (isMember && origin) {
+ res.setHeader("Set-Cookie", serializeProjectCookie({ origin, projectId }));
+ }
+
+ return res.status(204).end();
+}
diff --git a/web/src/pages/project/~/[[...path]].tsx b/web/src/pages/project/~/[[...path]].tsx
new file mode 100644
index 0000000000..dc953c9c4c
--- /dev/null
+++ b/web/src/pages/project/~/[[...path]].tsx
@@ -0,0 +1,120 @@
+import {
+ type GetServerSideProps,
+ type GetServerSidePropsContext,
+ type GetServerSidePropsResult,
+} from "next";
+
+import { getServerAuthSession } from "@/src/server/auth";
+import { type Session } from "next-auth";
+import {
+ getRequestOrigin,
+ readProjectCookie,
+ type ProjectCookie,
+} from "@/src/server/utils/cookies";
+
+/** RedirectToFirstProject renders nothing; all logic runs in getServerSideProps. */
+const RedirectToFirstProject = () => null;
+export default RedirectToFirstProject;
+
+/** getServerSideProps resolves the project sentinel: cross-region bounce, sign-in gate, then project redirect. */
+export const getServerSideProps: GetServerSideProps = async (ctx) => {
+ const sCtx = parseSentinelRequest(ctx);
+
+ const crossRegion = crossRegionRedirect(sCtx);
+ if (crossRegion) return crossRegion;
+
+ const signIn = await signInRedirect(sCtx);
+ if (signIn) return signIn;
+
+ return projectRedirect(sCtx);
+};
+
+/** parseSentinelRequest reads the cookie, origin, and resolved URL the sentinel needs, deferring the session to a memoized fetch. */
+const parseSentinelRequest = (
+ ctx: GetServerSidePropsContext,
+): SentinelContext => {
+ let session: Promise<Session | null> | undefined;
+ return {
+ cookie: readProjectCookie(ctx.req.cookies ?? {}),
+ origin: getRequestOrigin(ctx.req),
+ resolvedUrl: ctx.resolvedUrl,
+ getSession: () =>
+ (session ??= getServerAuthSession({ req: ctx.req, res: ctx.res })),
+ };
+};
+
+/** crossRegionRedirect bounces to the cookie's origin when it is a sibling region the session lives on. */
+const crossRegionRedirect = (req: SentinelContext) => {
+ const { cookie, origin, resolvedUrl } = req;
+ if (
+ cookie &&
+ origin &&
+ cookie.origin !== origin &&
+ sameRegistrableDomain(cookie.origin, origin)
+ ) {
+ return redirect(`${cookie.origin}${resolvedUrl}`);
+ }
+};
+
+/** signInRedirect sends the user to sign-in, returning to the sentinel URL afterward. */
+const signInRedirect = async ({ getSession, resolvedUrl }: SentinelContext) => {
+ const session = await getSession();
+ if (!session?.user)
+ return redirect(
+ `/auth/sign-in?callbackUrl=${encodeURIComponent(resolvedUrl)}`,
+ );
+};
+
+/** projectRedirect resolves to the last visited project, the first accessible project, or home if no projects are available. */
+const projectRedirect = async ({
+ cookie,
+ origin,
+ resolvedUrl,
+ getSession,
+}: SentinelContext) => {
+ const session = await getSession();
+ const rest = resolvedUrl.slice(sentinelPathPrefix.length);
+ const projects =
+ session?.user?.organizations.flatMap((org) => org.projects) ?? [];
+
+ if (cookie && origin && cookie.origin === origin) {
+ if (projects.some((p) => p.id === cookie.projectId)) {
+ return redirect(`/project/${cookie.projectId}${rest}`);
+ }
+ }
+
+ const firstProjectId = projects.at(0)?.id;
+ if (!firstProjectId) return redirect("/");
+
+ return redirect(`/project/${firstProjectId}${rest}`);
+};
+
+/** redirect wraps a destination in a non-permanent getServerSideProps redirect result. */
+const redirect = (destination: string): GetServerSidePropsResult<never> => ({
+ redirect: { destination, permanent: false },
+});
+
+/** sameRegistrableDomain returns true when two origins share the last-two-label registrable domain. */
+const sameRegistrableDomain = (originA: string, originB: string): boolean => {
+ const registrableDomain = (origin: string): string | null => {
+ try {
+ return new URL(origin).hostname.split(".").slice(-2).join(".");
+ } catch {
+ return null;
+ }
+ };
+ const domainA = registrableDomain(originA);
+ const domainB = registrableDomain(originB);
+ return domainA !== null && domainA === domainB;
+};
+
+/** sentinelPathPrefix is the route prefix stripped to recover the trailing path and query. */
+const sentinelPathPrefix = "/project/~";
+
+/** SentinelContext holds the request-derived inputs every redirect step reads. */
+type SentinelContext = {
+ cookie: ProjectCookie | null;
+ origin: string | null;
+ resolvedUrl: string;
+ getSession: () => Promise<Session | null>;
+};
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 92921330c6..091524e27f 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -762,6 +762,10 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
admin: true,
v4BetaEnabled: true,
organizationMemberships: {
+ // Newest first so demo project is last for the `project/~/` sentinel
+ orderBy: {
+ createdAt: "desc",
+ },
include: {
organization: {
include: {
@@ -771,6 +775,9 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
equals: null,
},
},
+ orderBy: {
+ createdAt: "desc",
+ },
},
},
},
diff --git a/web/src/server/utils/cookies.ts b/web/src/server/utils/cookies.ts
index e406548451..f486167c7b 100644
--- a/web/src/server/utils/cookies.ts
+++ b/web/src/server/utils/cookies.ts
@@ -1,5 +1,13 @@
+import { type IncomingMessage } from "http";
+
import { env } from "@/src/env.mjs";
+/** projectCookieName names the region-unscoped cookie recording a user's most recent project. */
+export const projectCookieName = "langfuse.project";
+
+/** projectCookieMaxAgeSeconds keeps the project cookie alive for 30 days. */
+const projectCookieMaxAgeSeconds = 60 * 60 * 24 * 30;
+
// Use secure cookies on https hostnames, exception for Vercel which sets NEXTAUTH_URL without the protocol
const shouldSecureCookies = () =>
env.NEXTAUTH_URL.startsWith("https://") || process.env.VERCEL === "1";
@@ -20,3 +28,70 @@ export const getCookieName = (name: string) =>
? `.${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}`
: "",
].join("");
+
+/** ProjectCookie carries the server-stamped origin and project id of a user's most recent project. */
+export type ProjectCookie = {
+ origin: string;
+ projectId: string;
+};
+
+/** getRequestOrigin derives the request's own origin from forwarded headers, never from client input. */
+export const getRequestOrigin = (req: IncomingMessage): string | null => {
+ const headers = req.headers;
+ const hostHeader = Array.isArray(headers.host)
+ ? headers.host[0]
+ : headers.host;
+ if (!hostHeader) return null;
+
+ const forwardedProto = Array.isArray(headers["x-forwarded-proto"])
+ ? headers["x-forwarded-proto"][0]
+ : headers["x-forwarded-proto"];
+ const proto =
+ forwardedProto?.split(",")[0]?.trim() ||
+ (shouldSecureCookies() ? "https" : "http");
+
+ try {
+ return new URL(`${proto}://${hostHeader}`).origin;
+ } catch {
+ return null;
+ }
+};
+
+/** readProjectCookie parses the project cookie, returning null when absent or malformed. */
+export const readProjectCookie = (
+ cookies: Partial<Record<string, string>>,
+): ProjectCookie | null => {
+ const raw = cookies[projectCookieName];
+ if (!raw) return null;
+
+ try {
+ const parsed = JSON.parse(raw) as unknown;
+ if (
+ typeof parsed === "object" &&
+ parsed !== null &&
+ typeof (parsed as ProjectCookie).origin === "string" &&
+ typeof (parsed as ProjectCookie).projectId === "string"
+ ) {
+ const { origin, projectId } = parsed as ProjectCookie;
+ return { origin, projectId };
+ }
+ } catch {
+ // malformed cookie -> treat as absent
+ }
+ return null;
+};
+
+/** serializeProjectCookie builds the Set-Cookie header value for the project cookie. */
+export const serializeProjectCookie = (value: ProjectCookie): string => {
+ const options = getCookieOptions();
+ const parts = [
+ `${projectCookieName}=${encodeURIComponent(JSON.stringify(value))}`,
+ `Path=${options.path}`,
+ "SameSite=Lax",
+ `Max-Age=${projectCookieMaxAgeSeconds}`,
+ ];
+ if (options.domain) parts.push(`Domain=${options.domain}`);
+ if (options.httpOnly) parts.push("HttpOnly");
+ if (options.secure) parts.push("Secure");
+ return parts.join("; ");
+};