# Next.js + Supabase Stack

> Full-stack Next.js application with self-hosted Supabase backend.

- Category: Full Web Stacks
- Difficulty: intermediate
- Components: nextjs, supabase-db, supabase-auth, supabase-storage, supabase-realtime
- Tags: nextjs, supabase, postgresql, realtime, auth
- Source: https://docker.recipes/full-stacks/next-supabase-stack

## Overview

Next.js is a production-ready React framework that enables server-side rendering, static site generation, and full-stack development capabilities with built-in API routes. Combined with Supabase's open-source backend-as-a-service platform, it creates a powerful full-stack development environment that rivals Firebase but with the flexibility of self-hosting and PostgreSQL as the underlying database.

This deployment creates a complete Supabase backend infrastructure alongside a Next.js frontend application. The stack includes seven specialized services: a Next.js application server, Kong API gateway for routing, GoTrue for authentication, PostgREST for automatic API generation, Realtime for WebSocket connections, Storage API for file management, and a PostgreSQL database. Kong acts as the central API gateway, routing requests from the Next.js app to the appropriate Supabase microservices, creating a cohesive development experience.

This configuration is ideal for developers who want the modern development experience of Supabase without vendor lock-in, teams building real-time applications that need instant database synchronization, and organizations requiring full control over their backend infrastructure. The combination provides type-safe database access, real-time subscriptions, user authentication, and file storage while maintaining the performance benefits of Next.js's hybrid rendering capabilities.

## Features

- GoTrue authentication service with JWT token management and social provider support
- PostgREST automatic API generation that creates RESTful endpoints directly from PostgreSQL schema
- Real-time database subscriptions through WebSocket connections for instant UI updates
- Supabase Storage API with file upload, transformation, and CDN capabilities
- Kong API gateway providing centralized routing and request management across all Supabase services
- Next.js server-side rendering with automatic API route integration to Supabase backend
- PostgreSQL database with Supabase extensions for row-level security and real-time functionality
- Type-safe database queries through auto-generated TypeScript definitions from schema

## Use cases

- Real-time collaborative applications like document editors, chat platforms, or project management tools
- SaaS applications requiring multi-tenant architecture with row-level security policies
- E-commerce platforms needing user authentication, product catalogs, and file storage for images
- Content management systems with real-time editing and media asset management
- Social media applications requiring user profiles, real-time feeds, and image uploads
- Educational platforms with user progress tracking and real-time collaboration features
- IoT dashboards displaying real-time sensor data with user authentication and data visualization

## Prerequisites

- Docker Engine 20.10+ and Docker Compose V2 for container orchestration
- 8GB RAM minimum for running all Supabase microservices simultaneously
- Node.js 18+ knowledge for Next.js development and API route customization
- PostgreSQL understanding for database schema design and row-level security policies
- Available ports 3000 (Next.js), 8000 (Kong gateway), and 8443 (Kong HTTPS)
- JWT secret generation capability and environment variable management experience

## docker-compose.yml

```yaml
services:
  nextjs:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    environment:
      NEXT_PUBLIC_SUPABASE_URL: http://localhost:8000
      NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}
      SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_KEY}
    depends_on:
      - kong
    networks:
      - supabase-net
    restart: unless-stopped

  kong:
    image: kong:latest
    ports:
      - "8000:8000"
      - "8443:8443"
    environment:
      KONG_DATABASE: "off"
      KONG_DECLARATIVE_CONFIG: /var/lib/kong/kong.yml
    volumes:
      - ./kong.yml:/var/lib/kong/kong.yml:ro
    networks:
      - supabase-net
    restart: unless-stopped

  auth:
    image: supabase/gotrue:latest
    environment:
      GOTRUE_API_HOST: 0.0.0.0
      GOTRUE_API_PORT: 9999
      GOTRUE_DB_DRIVER: postgres
      GOTRUE_DB_DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
      GOTRUE_SITE_URL: http://localhost:3000
      GOTRUE_JWT_SECRET: ${JWT_SECRET}
    depends_on:
      db:
        condition: service_healthy
    networks:
      - supabase-net
    restart: unless-stopped

  rest:
    image: postgrest/postgrest:latest
    environment:
      PGRST_DB_URI: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
      PGRST_DB_ANON_ROLE: anon
      PGRST_JWT_SECRET: ${JWT_SECRET}
    depends_on:
      db:
        condition: service_healthy
    networks:
      - supabase-net
    restart: unless-stopped

  realtime:
    image: supabase/realtime:latest
    environment:
      DB_HOST: db
      DB_PORT: 5432
      DB_USER: ${POSTGRES_USER}
      DB_PASSWORD: ${POSTGRES_PASSWORD}
      DB_NAME: ${POSTGRES_DB}
      PORT: 4000
      JWT_SECRET: ${JWT_SECRET}
    depends_on:
      db:
        condition: service_healthy
    networks:
      - supabase-net
    restart: unless-stopped

  storage:
    image: supabase/storage-api:latest
    environment:
      ANON_KEY: ${SUPABASE_ANON_KEY}
      SERVICE_KEY: ${SUPABASE_SERVICE_KEY}
      POSTGREST_URL: http://rest:3000
      PGRST_JWT_SECRET: ${JWT_SECRET}
      DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
      STORAGE_BACKEND: file
      FILE_STORAGE_BACKEND_PATH: /var/lib/storage
    volumes:
      - storage_data:/var/lib/storage
    depends_on:
      db:
        condition: service_healthy
      rest:
        condition: service_started
    networks:
      - supabase-net
    restart: unless-stopped

  db:
    image: supabase/postgres:latest
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - supabase-net
    restart: unless-stopped

volumes:
  postgres_data:
  storage_data:

networks:
  supabase-net:
    driver: bridge
```

## .env

```bash
# PostgreSQL
POSTGRES_USER=supabase
POSTGRES_PASSWORD=secure_postgres_password
POSTGRES_DB=supabase

# Supabase Keys
JWT_SECRET=your-super-secret-jwt-token-with-at-least-32-characters
SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

## Usage notes

- Generate JWT keys for Supabase authentication
- Next.js app at http://localhost:3000
- Supabase API at http://localhost:8000
- Create kong.yml for API gateway configuration

## Troubleshooting

- GoTrue authentication failing: Verify JWT_SECRET matches across auth, rest, and realtime services and ensure GOTRUE_SITE_URL points to correct Next.js origin
- PostgREST API returning 401 errors: Check that PGRST_DB_ANON_ROLE exists in PostgreSQL and JWT_SECRET environment variable is identical across services
- Real-time subscriptions not working: Confirm realtime service can connect to database and JWT_SECRET is properly configured for WebSocket authentication
- Storage API uploads failing: Ensure storage service has proper file system permissions for /var/lib/storage volume and PostgREST URL is accessible
- Kong gateway returning 502 errors: Verify all upstream Supabase services are healthy and kong.yml configuration file contains correct service definitions
- Next.js cannot connect to Supabase: Check NEXT_PUBLIC_SUPABASE_URL points to Kong gateway (port 8000) and SUPABASE_ANON_KEY matches the generated JWT token

