4 Hours

17. Supabase with Next.js (App Router)

Integration

Production Next.js + Supabase Architecture

The Next.js App Router (React Server Components) changes how Supabase is used compared to a traditional SPA. You need different Supabase client instances for Server Components, Client Components, Server Actions, and Route Handlers — each with the correct session handling strategy.

Next.js App Router uses Server Components by default. This is a shift from the traditional client-side rendering model. Server Components run on the server and can access the database directly. This reduces client-side JavaScript and improves performance. However, it also changes how authentication works. You need to manage sessions on the server using cookies. The @supabase/ssr package provides createServerClient for server components and createBrowserClient for client components. The middleware refreshes the session on every request. Server Actions provide type-safe mutations that run on the server. This architecture gives you the best of both worlds — secure server-side data access with a smooth client-side experience.

Two Clients, One Rule

The rule is: use createServerClient for server components, server actions, and route handlers. Use createBrowserClient for client components. The server client uses cookies for session management. The browser client uses localStorage or cookies. The server client reads cookies via the cookies() function from next/headers. The browser client reads cookies from the browser. The setAll method in the server client handles setting cookies on the response. This ensures the session stays in sync. The createBrowserClient is simpler — it just creates a client with the standard configuration. This separation of concerns is essential for correct SSR. Using the wrong client in the wrong context leads to session issues.

TypeScript
// lib/supabase/server.ts — for Server Components, Server Actions, Route Handlers
import { createServerClient } from '@supabase/ssr';
import { cookies } from 'next/headers';

export async function createSupabaseServer() {
  const cookieStore = await cookies();
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll: () => cookieStore.getAll(),
        setAll: (cookiesToSet) => {
          cookiesToSet.forEach(({ name, value, options }) =>
            cookieStore.set(name, value, options)
          );
        },
      },
    }
  );
}

// lib/supabase/client.ts — for Client Components only
import { createBrowserClient } from '@supabase/ssr';

export function createSupabaseBrowser() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  );
}

Middleware: Session Refresh on Every Request

Middleware runs on every request before rendering. It's the ideal place to refresh the session. The middleware creates a server client with the request cookies. It calls getUser() to validate and refresh the token. This ensures the session is always fresh. The middleware can also protect routes — if the user is not authenticated, it redirects to the login page. The matcher pattern defines which paths trigger the middleware. Always use getUser() not getSession() on the server. getUser() validates the token against the Auth server. getSession() only reads the cookie. The middleware is essential for maintaining secure sessions in Next.js applications.

TypeScript
// middleware.ts — runs on EVERY request before rendering
import { createServerClient } from '@supabase/ssr';
import { NextResponse } from 'next/server';

export async function middleware(request: NextRequest) {
  let supabaseResponse = NextResponse.next({ request });
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    { cookies: { getAll: () => request.cookies.getAll(), setAll: (cookiesToSet) =>
      cookiesToSet.forEach(({ name, value, options }) =>
        supabaseResponse.cookies.set(name, value, options)
      ) } }
  );
  const { data: { user } } = await supabase.auth.getUser();
  if (!user && request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return supabaseResponse;
}
Always use getUser() not getSession() on the server:getUser() validates the JWT against the Supabase Auth server — it cannot be spoofed. getSession() only reads the local cookie, which could be tampered with by a malicious user.

Server Components & Server Actions

Server Components are the backbone of the App Router. They run on the server and can query the database directly. This reduces client-side JavaScript and improves performance. In a Server Component, you create a server client, authenticate the user, and query the database. The data is rendered on the server and sent to the client as HTML. No API key or query details are exposed. Server Actions are functions marked with use server. They run on the server and can be called from forms or event handlers. Server Actions handle mutations securely. Always check authentication in Server Actions. RLS is your first line of defense, but also check ownership in code. This is defense in depth — even if RLS fails, your application code prevents unauthorized access.

TypeScript
// app/dashboard/page.tsx — React Server Component
import { createSupabaseServer } from '@/lib/supabase/server';
import { redirect } from 'next/navigation';

export default async function Dashboard() {
  const supabase = await createSupabaseServer();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) redirect('/login');
  const { data: posts } = await supabase
    .from('posts')
    .select('id, title, created_at')
    .eq('user_id', user.id);
  return <PostList posts={posts ?? []} />;
}

Knowledge Check

Ready to test your understanding of 17. Supabase with Next.js (App Router)?

Back