Subdomain Cookies Installation
Share authentication across subdomains with Next.js and Supabase
Installation
npx shadcn@latest add https://snippets.thedevdavid.com/r/next-supabase-subdomain-cookies.json
Prerequisites
Supabase Project
Create a project at supabase.com
Environment Variables
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
COOKIE_DOMAIN=.yourdomain.com # Note the leading dot!
COOKIE_DOMAIN
must start with a dot (.) for subdomain sharing
Configuration
1. Supabase Dashboard
Go to Authentication → Settings and add redirect URLs:
https://*.yourdomain.com/**
http://*.localhost:3000/** # for development
2. Update Middleware (Optional)
Customize protected routes in middleware.ts
:
// Already configured, but you can modify the matcher
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
Usage
Server Components
import { createClient } from "@/utils/supabase/server";
import { redirect } from "next/navigation";
export default async function Dashboard() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) redirect("/auth");
return <div>Welcome, {user.email}!</div>;
}
Client Components
"use client";
import { createClient } from "@/utils/supabase/client";
import { useRouter } from "next/navigation";
export function SignOut() {
const router = useRouter();
const supabase = createClient();
const handleSignOut = async () => {
await supabase.auth.signOut();
router.push("/auth");
};
return <button onClick={handleSignOut}>Sign Out</button>;
}
Testing
Verify
- Sign in on
auth.localhost:3000
- Navigate to
app.localhost:3000
- You should remain authenticated
Common Issues
Cookies not sharing?
- Check
COOKIE_DOMAIN
starts with.
- Verify redirect URLs in Supabase include wildcards
- Use HTTPS in production
Session not persisting?
- Check middleware is running on all routes
- Verify cookie settings match your domain
Resources
How is this guide?
Last updated: 6/2/2025
Last updated on