Honestly, I just wanted a nice rainbow gradient banner at the top.

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

.env.local
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:

middleware.ts
// Already configured, but you can modify the matcher
export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};

Usage

Server Components

app/dashboard/page.tsx
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

components/sign-out.tsx
"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

Local Setup

Add to your hosts file:

127.0.0.1 app.localhost
127.0.0.1 auth.localhost

Verify

  1. Sign in on auth.localhost:3000
  2. Navigate to app.localhost:3000
  3. 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