Add Supabase authentication to TanStack Start
Sign in with Supabase Auth and carry the session through server requests with cookies in TanStack Start.
A sign-in form is useful only if the next request still identifies the user. This guide signs in an existing Supabase test account with a password, writes its session cookies in the response, and checks the user on a later request. The server handles credentials; the browser never receives a Supabase secret key.
Before you start
You need a TypeScript TanStack Start app, a Supabase project with email/password sign-in enabled, and a confirmed test user. Create a separate test account rather than using a real customer's credentials. Install the server client and cookie parser:
bun add @supabase/supabase-js @supabase/ssr cookie-esSet SUPABASE_URL and SUPABASE_PUBLISHABLE_KEY in the app server's environment using the values from your project. These identify the project; they are not a substitute for authorization. Never put a secret or service-role key in browser code. Supabase's server-side guide explains the cookie-backed server client.
Give the server client request and response cookies
Create :
import '@tanstack/react-start/server-only'
import { createServerClient } from '@supabase/ssr'
import {
getCookies, getResponseHeaders, setCookie, setResponseHeader,
} from '@tanstack/react-start/server'
import { parseSetCookie } from 'cookie-es'
export function supabaseServer() {
const url = process.env.SUPABASE_URL
const key = process.env.SUPABASE_PUBLISHABLE_KEY
if (!url || !key) throw new Error('Missing Supabase configuration')
setResponseHeader('Cache-Control', 'private, no-store')
return createServerClient(url, key, {
cookies: {
getAll() {
const cookies = getCookies()
// Include cookies already changed during this response.
for (const header of getResponseHeaders().getSetCookie()) {
const cookie = parseSetCookie(header)
if (cookie) cookies[cookie.name] = cookie.value
}
return Object.entries(cookies).map(([name, value]) => ({ name, value }))
},
setAll(cookiesToSet, headers) {
cookiesToSet.forEach(({ name, value, options }) => setCookie(name, value, options))
Object.entries(headers).forEach(([name, value]) => setResponseHeader(name, value))
},
},
})
}Create this client within each request, not as a shared singleton. The cache header marks the response private and non-storable even when the session does not refresh. getAll reads request cookies and pending response changes; setAll passes session changes to the outgoing response. Dropping Set-Cookie during a redirect or proxy hop can make sign-in look successful while the next request is anonymous. Match the @supabase/ssr cookie API to your installed version.
Protect server-function mutations
Set APP_ORIGIN in the server environment to the exact public app origin, for example http://localhost:3000 for local development. Add this to , or merge the middleware into your existing createStart configuration:
import { createCsrfMiddleware, createStart } from '@tanstack/react-start'
export const startInstance = createStart(() => ({
requestMiddleware: [
createCsrfMiddleware({
filter: ({ handlerType }) => handlerType === 'serverFn',
origin: (origin) => Boolean(process.env.APP_ORIGIN) && origin === process.env.APP_ORIGIN,
}),
],
}))The middleware checks Sec-Fetch-Site first and, by default, accepts same-origin. When that header is absent, it checks Origin against APP_ORIGIN, or the Referer origin if Origin is also absent. It rejects the request if none is available. Use the externally visible HTTPS origin behind a proxy; do not derive the trusted value from a caller's headers. This protects the server-function mutations below. API server routes, and any API framework you mount, need their own mutation guard. See TanStack Start middleware.
Sign in and check the next request
Create :
import { createFileRoute } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { useEffect, useState } from 'react'
const signIn = createServerFn({ method: 'POST' })
.validator((input: { email: string; password: string }) => {
if ('string' !== typeof input?.email || 'string' !== typeof input?.password) {
throw new Error('Invalid input')
}
return { email: input.email.trim(), password: input.password }
})
.handler(async ({ data }) => {
const { supabaseServer } = await import('../lib/supabase-server')
const { error } = await supabaseServer().auth.signInWithPassword(data)
return { ok: !error }
})
const currentUser = createServerFn({ method: 'GET' }).handler(async () => {
const { supabaseServer } = await import('../lib/supabase-server')
const { data, error } = await supabaseServer().auth.getUser()
return { email: error ? null : data.user?.email ?? null }
})
const signOut = createServerFn({ method: 'POST' }).handler(async () => {
const { supabaseServer } = await import('../lib/supabase-server')
const { error } = await supabaseServer().auth.signOut()
return { ok: !error }
})
export const Route = createFileRoute('/sign-in')({
loader: () => currentUser(),
component: SignInPage,
})
function SignInPage() {
const user = Route.useLoaderData()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [message, setMessage] = useState('')
// Keep the button disabled until React handles the submit.
const [ready, setReady] = useState(false)
useEffect(() => setReady(true), [])
return <main>
<h1>Sign in</h1>
{user.email ? <>
<p>Signed in as {user.email}</p>
<button onClick={async () => {
const result = await signOut()
if (result.ok) window.location.reload()
else setMessage('Could not sign out')
}}>Sign out</button>
</> : <form onSubmit={async (event) => {
event.preventDefault()
try {
const result = await signIn({ data: { email, password } })
setPassword('')
if (result.ok) window.location.reload()
else setMessage('Sign-in failed')
} catch {
setPassword('')
setMessage('Sign-in failed')
}
}}>
<label>Email <input type="email" required value={email} onChange={e => setEmail(e.target.value)} /></label>
<label>Password <input type="password" required value={password} onChange={e => setPassword(e.target.value)} /></label>
<button type="submit" disabled={!ready}>Sign in</button>
</form>}
{message && <p role="alert">{message}</p>}
</main>
}The button stays disabled until the page is interactive, so an early click cannot fall back to a plain browser form submission that skips the sign-in call. Rate-limit sign-in and avoid logging credentials. The example returns a generic failure so it does not disclose whether an account exists.
Start the app, open /sign-in, and sign in with the test account. The page reload should show its email. Reload again to check persistence, then sign out and reload to see the form. Try a wrong password and confirm that the page does not report a signed-in user. Do not paste cookie values or credentials into logs or support requests.
getUser() asks Supabase to validate the user; a locally read session alone is not an authorization decision. Even a valid identity does not establish permission to access a particular record. Check that permission in each protected server operation. See Supabase's user verification guidance.
For email links instead of passwords, follow the magic-link session checks. The CoreMVP TanStack Start premium template includes the server client, session refresh and sign-in path, so you can start from an existing cookie boundary. You still configure your own Supabase project and protect your own data. See project structure.