Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
refactor(auth): move session redirects to middleware and add client-side session UI
Richard Reis082396258638
diff --git a/proxy.ts b/proxy.tsindex 06178e0..c603b3d 100644--- a/proxy.ts+++ b/proxy.ts@@ -1,4 +1,5 @@import type { NextRequest } from "next/server";+import { getCookieCache, getSessionCookie } from "better-auth/cookies";import { NextResponse } from "next/server";const DEFAULT_PERMISSIONS_POLICY = [@@ -72,7 +73,56 @@ function applySecurityHeaders(response: NextResponse, pathname: string) {return response;}-export function proxy(request: NextRequest) {+async function hasOptimisticSession(request: NextRequest) {+ if (process.env.BETTER_AUTH_SECRET) {+ try {+ const session = await getCookieCache(request, {+ secret: process.env.BETTER_AUTH_SECRET,+ });++ if (session) {+ return true;+ }+ } catch {+ // Fall back to the session token check if cookie-cache parsing fails.+ }+ }++ return getSessionCookie(request) !== null;+}++async function maybeRedirectAuthenticatedAuthRoute(request: NextRequest) {+ const pathname = request.nextUrl.pathname;++ if (pathname !== "/login" && pathname !== "/signup") {+ return null;+ }++ if (pathname === "/login") {+ const hasResetState =+ request.nextUrl.searchParams.has("token") ||+ request.nextUrl.searchParams.has("error");++ if (hasResetState) {+ return null;+ }+ }++ const hasSession = await hasOptimisticSession(request);++ if (!hasSession) {+ return null;+ }++ const dashboardUrl = request.nextUrl.clone();++ dashboardUrl.pathname = "/dashboard";+ dashboardUrl.search = "";++ return NextResponse.redirect(dashboardUrl);+}++export async function proxy(request: NextRequest) {const pathname = request.nextUrl.pathname;const forwardedProto = request.headers.get("x-forwarded-proto")@@ -97,6 +147,12 @@ export function proxy(request: NextRequest) {return applySecurityHeaders(NextResponse.redirect(httpsUrl), pathname);}+ const authRedirect = await maybeRedirectAuthenticatedAuthRoute(request);++ if (authRedirect) {+ return applySecurityHeaders(authRedirect, pathname);+ }+return applySecurityHeaders(NextResponse.next(), pathname);}diff --git a/src/app/(auth)/login/page.tsx b/src/app/(auth)/login/page.tsxindex d3054a4..725f8c4 100644--- a/src/app/(auth)/login/page.tsx+++ b/src/app/(auth)/login/page.tsx@@ -1,7 +1,4 @@-import { redirect } from "next/navigation";-import { LoginShell } from "@/components/auth/login-shell";-import { getAuthSession } from "@/lib/auth/server";type LoginPageProps = {searchParams?: Promise<{@@ -12,17 +9,6 @@ type LoginPageProps = {export default async function LoginPage({ searchParams }: LoginPageProps) {const resolvedSearchParams = searchParams ? await searchParams : undefined;- const hasLiveAuthState =- resolvedSearchParams?.token !== undefined ||- resolvedSearchParams?.error !== undefined;-- if (!hasLiveAuthState) {- const session = await getAuthSession();-- if (session) {- redirect("/dashboard");- }- }return (<LoginShelldiff --git a/src/app/(auth)/signup/page.tsx b/src/app/(auth)/signup/page.tsxindex 67f481a..e0b9f34 100644--- a/src/app/(auth)/signup/page.tsx+++ b/src/app/(auth)/signup/page.tsx@@ -1,14 +1,5 @@-import { redirect } from "next/navigation";-import { SignupShell } from "@/components/auth/signup-shell";-import { getAuthSession } from "@/lib/auth/server";--export default async function SignupPage() {- const session = await getAuthSession();-- if (session) {- redirect("/dashboard");- }+export default function SignupPage() {return <SignupShell />;}diff --git a/src/app/page.tsx b/src/app/page.tsxindex 2448981..8818d56 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -1,5 +1,5 @@import { LandingShell } from "@/components/landing/landing-shell";export default function Home() {- return <LandingShell initialState="default" />;+ return <LandingShell />;}diff --git a/src/components/auth/login-shell.tsx b/src/components/auth/login-shell.tsxindex f9c16f0..bd898d8 100644--- a/src/components/auth/login-shell.tsx+++ b/src/components/auth/login-shell.tsx@@ -1,6 +1,7 @@"use client";import Link from "next/link";+import { useRouter } from "next/navigation";import { useState, type ChangeEvent, type FormEvent } from "react";import { FieldShell, ShellButton } from "@/components/shared/form-shell";@@ -110,6 +111,7 @@ function LiveLoginShell({resetError = null,resetToken = null,}: LoginShellProps) {+ const router = useRouter();const [values, setValues] = useState<LoginFormValues>(createLoginFormValues(),);@@ -214,7 +216,6 @@ function LiveLoginShell({setIsSubmitting(true);const result = await authClient.signIn.email({- callbackURL: `${window.location.origin}/dashboard`,email: validationResult.data.email,password: validationResult.data.password,});@@ -236,7 +237,7 @@ function LiveLoginShell({return;}- window.location.assign("/dashboard");+ router.replace("/dashboard");}async function handleForgotPasswordSubmit(event: FormEvent<HTMLFormElement>) {diff --git a/src/components/landing/landing-session-actions.tsx b/src/components/landing/landing-session-actions.tsxnew file mode 100644index 0000000..1a26d2c--- /dev/null+++ b/src/components/landing/landing-session-actions.tsx@@ -0,0 +1,77 @@+"use client";++import Link from "next/link";++import { authClient } from "@/lib/auth/client";+import { cn } from "@/lib/cn";++type LandingSessionActionProps = {+ className?: string;+ monoClassName: string;+};++export function LandingSessionPrimaryAction({+ className,+ monoClassName,+}: LandingSessionActionProps) {+ const { data: session } = authClient.useSession();+ const authenticated = !!session;++ return (+ <Link+ className={landingActionLinkClassName({+ className,+ monoClassName,+ variant: "primary",+ })}+ href={authenticated ? "/dashboard" : "/signup"}+ prefetch+ style={{ color: "#fff" }}+ >+ {authenticated ? "Go to dashboard" : "Start free"}+ </Link>+ );+}++export function LandingSessionLoginAction({+ className,+ monoClassName,+}: LandingSessionActionProps) {+ const { data: session } = authClient.useSession();++ if (session) {+ return null;+ }++ return (+ <Link+ className={landingActionLinkClassName({+ className,+ monoClassName,+ variant: "secondary",+ })}+ href="/login"+ prefetch+ >+ Log in+ </Link>+ );+}++function landingActionLinkClassName({+ className,+ monoClassName,+ variant,+}: {+ className?: string;+ monoClassName: string;+ variant: "primary" | "secondary";+}) {+ return cn(+ `${monoClassName} inline-flex items-center justify-center border-2 px-5 py-3 text-sm font-bold uppercase tracking-[0.16em] transition-colors`,+ variant === "primary"+ ? "border-[#e50000] bg-[#e50000] text-white hover:border-[#c00000] hover:bg-[#c00000]"+ : "border-[#d4d4d4] bg-transparent text-black hover:border-black",+ className,+ );+}diff --git a/src/components/landing/landing-shell.tsx b/src/components/landing/landing-shell.tsxindex e68faab..57d6692 100644--- a/src/components/landing/landing-shell.tsx+++ b/src/components/landing/landing-shell.tsx@@ -11,9 +11,13 @@ import {X,} from "lucide-react";+import { PublicSessionMenu } from "@/components/layout/public-session-menu";import { PublicLegalFooter } from "@/components/layout/public-legal-links";import { LandingDashboardPreview } from "@/components/landing/dashboard-preview";-import { resolveShellState } from "@/components/shared/shell-state";+import {+ LandingSessionLoginAction,+ LandingSessionPrimaryAction,+} from "@/components/landing/landing-session-actions";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Separator } from "@/components/ui/separator";@@ -39,14 +43,6 @@ const ibmPlexMono = IBM_Plex_Mono({weight: ["400", "500", "600", "700"],});-export const landingShellStates = ["default", "authenticated"] as const;--export type LandingShellState = (typeof landingShellStates)[number];--type LandingShellProps = {- initialState?: LandingShellState | string | string[] | null;-};-type WorkflowStep = {body: string;title: string;@@ -145,18 +141,8 @@ const securityPillars: readonly SecurityPillar[] = [},];-export function resolveLandingShellState(- value?: string | string[] | null,-): LandingShellState {- return resolveShellState(value, landingShellStates, "default");-}--export function LandingShell({ initialState = "default" }: LandingShellProps) {- const resolvedInitialState = resolveLandingShellState(initialState);- const authenticated = resolvedInitialState === "authenticated";+export function LandingShell() {const monoClassName = ibmPlexMono.className;- const primaryHref = authenticated ? "/dashboard" : "/signup";- const primaryLabel = authenticated ? "Go to dashboard" : "Start free";const secondaryLabel = "See how it works";return (@@ -177,30 +163,35 @@ export function LandingShell({ initialState = "default" }: LandingShellProps) {<div className="mx-auto flex max-w-[1200px] flex-wrap items-center justify-between gap-4 px-6 py-5 sm:px-8 lg:px-10"><LandingWordmark />- <nav className="hidden flex-wrap items-center gap-3 sm:flex">- {!authenticated ? (+ <PublicSessionMenu+ buttonClassName="hidden rounded-none border-[#d4d4d4] bg-white text-black hover:border-black hover:bg-white hover:text-black sm:inline-flex"+ contentClassName="rounded-none border-[#d4d4d4] bg-white text-black"+ >+ <nav className="hidden flex-wrap items-center gap-3 sm:flex"><LinkclassName={`${monoClassName} text-sm font-medium text-[#71717a] transition-colors hover:text-black`}href="/login"+ prefetch>Log in</Link>- ) : null}- <ActionLink- href={primaryHref}- monoClassName={monoClassName}- variant="primary"- >- {primaryLabel}- </ActionLink>- </nav>-- <MobileNavigationMenu- authenticated={authenticated}- monoClassName={monoClassName}- primaryHref={primaryHref}- primaryLabel={primaryLabel}- />+ <ActionLink+ href="/signup"+ monoClassName={monoClassName}+ prefetch+ variant="primary"+ >+ Start free+ </ActionLink>+ </nav>+ </PublicSessionMenu>++ <PublicSessionMenu+ buttonClassName="rounded-none border-[#d4d4d4] bg-white text-black hover:border-black hover:bg-white hover:text-black sm:hidden"+ contentClassName="rounded-none border-[#d4d4d4] bg-white text-black"+ >+ <MobileNavigationMenu monoClassName={monoClassName} />+ </PublicSessionMenu></div></header>@@ -236,13 +227,7 @@ export function LandingShell({ initialState = "default" }: LandingShellProps) {</p><div className="mt-10 flex flex-wrap items-center justify-center gap-4">- <ActionLink- href={primaryHref}- monoClassName={monoClassName}- variant="primary"- >- {primaryLabel}- </ActionLink>+ <LandingSessionPrimaryAction monoClassName={monoClassName} /><ActionLinkhref="#workflow"monoClassName={monoClassName}@@ -344,13 +329,7 @@ export function LandingShell({ initialState = "default" }: LandingShellProps) {</div><div className="mt-10 flex flex-col items-center gap-4 text-center">- <ActionLink- href={primaryHref}- monoClassName={monoClassName}- variant="primary"- >- {primaryLabel}- </ActionLink>+ <LandingSessionPrimaryAction monoClassName={monoClassName} /><pclassName={`${monoClassName} text-[11px] uppercase tracking-[0.18em] text-[#71717a]`}>@@ -400,22 +379,8 @@ export function LandingShell({ initialState = "default" }: LandingShellProps) {</p><div className="mt-10 flex flex-wrap justify-center gap-4">- <ActionLink- href={primaryHref}- monoClassName={monoClassName}- variant="primary"- >- {primaryLabel}- </ActionLink>- {!authenticated ? (- <ActionLink- href="/login"- monoClassName={monoClassName}- variant="secondary"- >- Log in- </ActionLink>- ) : null}+ <LandingSessionPrimaryAction monoClassName={monoClassName} />+ <LandingSessionLoginAction monoClassName={monoClassName} /></div><p@@ -460,17 +425,20 @@ function ActionLink({children,href,monoClassName,+ prefetch,variant,}: {children: ReactNode;href: string;monoClassName: string;+ prefetch?: boolean;variant: "primary" | "secondary";}) {return (<LinkclassName={actionLinkClassName({ monoClassName, variant })}href={href}+ prefetch={prefetch}style={variant === "primary" ? { color: "#fff" } : undefined}>{children}@@ -496,17 +464,7 @@ function actionLinkClassName({);}-function MobileNavigationMenu({- authenticated,- monoClassName,- primaryHref,- primaryLabel,-}: {- authenticated: boolean;- monoClassName: string;- primaryHref: string;- primaryLabel: string;-}) {+function MobileNavigationMenu({ monoClassName }: { monoClassName: string }) {return (<Sheet><SheetTrigger asChild>@@ -543,27 +501,27 @@ function MobileNavigationMenu({monoClassName,variant: "primary",})}- href={primaryHref}+ href="/signup"+ prefetchstyle={{ color: "#fff" }}>- {primaryLabel}+ Start free</Link></SheetClose>- {!authenticated ? (- <SheetClose asChild>- <Link- className={actionLinkClassName({- className: "w-full",- monoClassName,- variant: "secondary",- })}- href="/login"- >- Log in- </Link>- </SheetClose>- ) : null}+ <SheetClose asChild>+ <Link+ className={actionLinkClassName({+ className: "w-full",+ monoClassName,+ variant: "secondary",+ })}+ href="/login"+ prefetch+ >+ Log in+ </Link>+ </SheetClose></nav></SheetContent></Sheet>diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsxindex 3682bd3..8afe53c 100644--- a/src/components/layout/app-shell.tsx+++ b/src/components/layout/app-shell.tsx@@ -1,7 +1,7 @@"use client";import Link from "next/link";-import { usePathname } from "next/navigation";+import { usePathname, useRouter } from "next/navigation";import {useState,type ComponentProps,@@ -61,6 +61,7 @@ const sectionLabelMap: Record<ShellSection, string> = {export function AppShell({ children, user }: AppShellProps) {const pathname = usePathname() ?? "/dashboard";+ const router = useRouter();const [isSigningOut, setIsSigningOut] = useState(false);const currentSection = resolveSection(pathname);const initials = getInitials(user.name);@@ -72,14 +73,17 @@ export function AppShell({ children, user }: AppShellProps) {setIsSigningOut(true);- const result = await authClient.signOut();+ const result = await authClient.signOut({+ fetchOptions: {+ onSuccess: () => {+ router.replace("/login");+ },+ },+ });if (result.error) {setIsSigningOut(false);- return;}-- window.location.assign("/login");}return (diff --git a/src/components/layout/auth-shell.tsx b/src/components/layout/auth-shell.tsxindex 12a319a..9bb2d39 100644--- a/src/components/layout/auth-shell.tsx+++ b/src/components/layout/auth-shell.tsx@@ -6,6 +6,7 @@ import type { ReactNode } from "react";import { Brand } from "@/components/layout/brand";import { PublicLegalFooter } from "@/components/layout/public-legal-links";+import { PublicSessionMenu } from "@/components/layout/public-session-menu";type AuthShellProps = {children: ReactNode;@@ -43,12 +44,15 @@ export function AuthShell({ children }: AuthShellProps) {aria-label="Public navigation"className="flex items-center gap-3">- <Link- className="editorial-meta transition-colors hover:text-(--fg)"- href={navAction.href}- >- {navAction.label}- </Link>+ <PublicSessionMenu>+ <Link+ className="editorial-meta transition-colors hover:text-(--fg)"+ href={navAction.href}+ prefetch+ >+ {navAction.label}+ </Link>+ </PublicSessionMenu></nav></div></header>diff --git a/src/components/layout/public-document-shell.tsx b/src/components/layout/public-document-shell.tsxindex 3348bbb..c07eb4c 100644--- a/src/components/layout/public-document-shell.tsx+++ b/src/components/layout/public-document-shell.tsx@@ -2,6 +2,7 @@ import type { ReactNode } from "react";import { Brand } from "@/components/layout/brand";import { PublicLegalFooter } from "@/components/layout/public-legal-links";+import { PublicSessionMenu } from "@/components/layout/public-session-menu";type PublicDocumentShellProps = {children: ReactNode;@@ -19,8 +20,9 @@ export function PublicDocumentShell({return (<div className="flex min-h-screen flex-col bg-white text-(--fg)"><header className="border-b border-(--border) bg-white">- <div className="editorial-shell flex items-center px-0 py-5">+ <div className="editorial-shell flex items-center justify-between gap-4 px-0 py-5"><Brand href="/" />+ <PublicSessionMenu /></div></header>diff --git a/src/components/layout/public-session-menu.tsx b/src/components/layout/public-session-menu.tsxnew file mode 100644index 0000000..19cdec8--- /dev/null+++ b/src/components/layout/public-session-menu.tsx@@ -0,0 +1,136 @@+"use client";++import Link from "next/link";+import { useState, type ReactNode } from "react";+import {+ CircleUserRound,+ LayoutDashboard,+ LogOut,+} from "lucide-react";++import { Avatar, AvatarFallback } from "@/components/ui/avatar";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { authClient } from "@/lib/auth/client";+import { cn } from "@/lib/cn";++type PublicSessionMenuProps = {+ align?: "center" | "end" | "start";+ buttonClassName?: string;+ children?: ReactNode;+ contentClassName?: string;+};++export function PublicSessionMenu({+ align = "end",+ buttonClassName,+ children = null,+ contentClassName,+}: PublicSessionMenuProps) {+ const { data: session } = authClient.useSession();+ const [isSigningOut, setIsSigningOut] = useState(false);++ if (!session) {+ return <>{children}</>;+ }++ const initials = getInitials(session.user.name);++ async function handleSignOut() {+ if (isSigningOut) {+ return;+ }++ setIsSigningOut(true);++ const result = await authClient.signOut();++ if (result.error) {+ setIsSigningOut(false);+ }+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ aria-label="Open account menu"+ className={cn(+ "rounded-none border border-(--border) bg-white text-(--fg) shadow-none hover:border-black hover:bg-white hover:text-(--fg)",+ buttonClassName,+ )}+ size="icon-sm"+ variant="outline"+ >+ <Avatar className="size-8 rounded-none bg-[#fff8f8] text-(--accent)">+ <AvatarFallback className="bg-[#fff8f8] text-sm font-semibold text-(--accent)">+ {initials ? (+ initials+ ) : (+ <CircleUserRound className="size-4 text-(--accent)" />+ )}+ </AvatarFallback>+ </Avatar>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align={align}+ className={cn(+ "w-56 rounded-none border border-(--border) bg-white p-2 shadow-none",+ contentClassName,+ )}+ >+ <DropdownMenuLabel className="px-3 py-2">+ <p className="truncate text-sm font-semibold text-(--fg)">+ {session.user.name}+ </p>+ <p className="mt-1 truncate text-xs font-normal text-(--tertiary)">+ {session.user.email}+ </p>+ </DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuItem asChild>+ <Link+ className="rounded-xl px-3 py-2 text-sm font-medium text-(--fg)"+ href="/dashboard"+ prefetch+ >+ <LayoutDashboard className="size-4" />+ Dashboard+ </Link>+ </DropdownMenuItem>+ <DropdownMenuItem+ className="rounded-xl px-3 py-2 text-sm font-medium text-(--accent)"+ disabled={isSigningOut}+ onSelect={(event) => {+ event.preventDefault();+ void handleSignOut();+ }}+ variant="destructive"+ >+ <LogOut className="size-4" />+ {isSigningOut ? "Signing out..." : "Log out"}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function getInitials(name: string) {+ const trimmedName = name.trim();++ if (!trimmedName) {+ return "";+ }++ const [first = "", second = ""] = trimmedName.split(/\s+/, 2);++ return `${first[0] ?? ""}${second[0] ?? first[1] ?? ""}`.toUpperCase();+}diff --git a/src/lib/auth/client.ts b/src/lib/auth/client.tsindex cc27458..2f75fd4 100644--- a/src/lib/auth/client.ts+++ b/src/lib/auth/client.ts@@ -2,6 +2,4 @@import { createAuthClient } from "better-auth/react";-export const authClient = createAuthClient({- disableDefaultFetchPlugins: true,-});+export const authClient = createAuthClient();diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.tsindex 36274a0..a60df61 100644--- a/src/lib/auth/server.ts+++ b/src/lib/auth/server.ts@@ -3,6 +3,7 @@ import { nextCookies } from "better-auth/next-js";import { haveIBeenPwned } from "better-auth/plugins";import { headers } from "next/headers";import type { Pool } from "pg";+import { cache } from "react";import { getDb } from "../db/connection.ts";import {@@ -146,7 +147,6 @@ export function createAppAuth({const authEnv = appEnv.auth;const emailService = createEmailService({ env });const plugins = [- ...(includeNextCookies ? [nextCookies()] : []),...(env.NODE_ENV === "production"? [haveIBeenPwned({@@ -155,6 +155,7 @@ export function createAppAuth({}),]: []),+ ...(includeNextCookies ? [nextCookies()] : []),];const secret = authEnv.betterAuthSecret!;@@ -220,6 +221,13 @@ export function createAppAuth({});},},+ session: {+ cookieCache: {+ enabled: true,+ maxAge: 5 * 60,+ },+ deferSessionRefresh: true,+ },plugins,secret,user: {@@ -257,8 +265,12 @@ export async function getAuthSessionFromHeaders(requestHeaders: Headers) {});}-export async function getAuthSession() {+const getCachedAuthSession = cache(async () => {const requestHeaders = await headers();return getAuthSessionFromHeaders(requestHeaders);+});++export function getAuthSession() {+ return getCachedAuthSession();}