If you are like me, you are tired of setting up the same Authentication boilerplate for every new project.
Connecting Next.js 14 (App Router) with Supabase requires a specific setup to handle Cookies correctly during Server-Side Rendering (SSR). If you get it wrong, your user sessions won't persist, or you'll get hydration errors.
I spent this weekend finalizing a clean server.ts utility that handles this perfectly. I'm sharing it here so you can just copy-paste it into your utils/supabase folder.
The Code
First, make sure you have the packages installed:
npm install @supabase/ssr @supabase/supabase-js
Then, create a file at utils/supabase/server.ts and drop this in:
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { cookies } from 'next/headers'
export async function createClient() {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
// Return null if Supabase is not configured
if (!supabaseUrl || !supabaseAnonKey) {
return null
}
const cookieStore = await cookies()
return createServerClient(
supabaseUrl,
supabaseAnonKey,
{
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet: { name: string; value: string; options: CookieOptions }[]) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options)
)
} catch {
// The `setAll` method was called from a Server Component.
// This can be ignored if you have middleware refreshing
// user sessions.
}
},
},
}
)
}
Why this works
The magic happens in the setAll method. In Next.js Server Components, you cannot write cookies (only read them). This helper detects that context. If you try to set a cookie from a Server Component, the try/catch block safely ignores it, preventing your app from crashing, while still allowing Middleware to handle the session refresh.
Want to skip the setup entirely?
I realized I was rewriting this logic (plus Stripe, Tailwind, and Auth forms) every single time I started a project.
So I built a complete Next.js + Supabase Starter Kit that has all of this pre-configured, including:
✅ Supabase Auth (Google + Email)
✅ Stripe Subscription Payments
✅ Tailwind Dashboard & Landing Page
✅ Fully Typed (TypeScript)
It saves about 3-4 days of setup time.
You can grab the Starter Kit here
(P.S. I added a discount code FIRST10 for %50 OFF for the first 10 people from this community!)
Top comments (0)