Skip to main content
Learn how to integrate Supabase with Next.js using the App Router, Server Components, and Server Actions for a modern, full-stack development experience.

Why Next.js + Supabase?

Next.js and Supabase work perfectly together:
  • Server Components for secure data fetching
  • Server Actions for mutations
  • Middleware for auth protection
  • Edge Runtime support
  • Type safety with TypeScript

Quick Start

1

Create a Next.js App

Choose:
  • TypeScript: Yes
  • App Router: Yes
  • Tailwind CSS: Yes (recommended)
2

Install Supabase

3

Set Up Environment Variables

Create .env.local:
4

Create Supabase Clients

Create lib/supabase/client.ts for Client Components:
Create lib/supabase/server.ts for Server Components:
Create lib/supabase/middleware.ts for Middleware:
5

Set Up Middleware

Create middleware.ts in your project root:

Usage Patterns

Fetch data securely in Server Components:

Client Components

Use Client Components for interactivity:

Server Actions

Handle mutations with Server Actions:
Use in components:

Route Handlers

Create API routes:

Authentication

Sign Up/Sign In

Create app/login/actions.ts:

Protected Routes

Protect pages in Server Components:

OAuth Providers

Sign in with OAuth:
Create callback handler at app/auth/callback/route.ts:

Real-time Subscriptions

Subscribe to changes in Client Components:

Type Safety

Generate types from your database:
Use types:

Best Practices

Use Server Components

Fetch data in Server Components when possible for better security and performance.

Server Actions for Mutations

Use Server Actions instead of Route Handlers for form submissions and mutations.

Client Components for Interactivity

Use Client Components only when you need hooks, event handlers, or browser APIs.

Middleware for Auth

Use middleware to refresh auth sessions automatically.

Type Generation

Generate TypeScript types from your database schema.

Next Steps

Build a Todo App

Follow our step-by-step tutorial

User Management

Add user profiles and avatars

File Uploads

Integrate Supabase Storage

Realtime Chat

Build a chat application