DEV Community

Cover image for How I Built a Production-Ready AI SaaS Boilerplate with Next.js 14 & Python FastAPI
Alexandre T.
Alexandre T.

Posted on

How I Built a Production-Ready AI SaaS Boilerplate with Next.js 14 & Python FastAPI

Every time I set out to build an AI SaaS application, I hit the exact same brick wall.

I didn't want to spend my first 3 days setting up:

  • PostgreSQL connection pools & reconnect retry mechanisms
  • JWT authentication with Bcrypt password hashing
  • Stripe Checkout sessions and robust webhook listeners
  • Docker Compose synchronization so the DB doesn't crash on cold boot

Most boilerplates in the market focus solely on Node.js / Next.js. But if you are doing serious AI work (LangChain, LlamaIndex, fine-tuning, PyTorch, async workers), Python is the undisputed king.

So I built AI-Flow — a production-ready boilerplate uniting Next.js 14 App Router with Python FastAPI and PostgreSQL.

Here is an architectural breakdown of how it works under the hood.


1. The Architecture Breakdown

A clean SaaS architecture must decouple the frontend UX from the AI computing backend:

┌──────────────────────────────────────────────┐
│        Next.js 14 Frontend (App Router)      │
│  - Tailwind CSS & Dark Mode UI               │
│  - Centralized API Client (Bearer Tokens)    │
│  - Dashboard & Stripe Upgrade UI             │
└──────────────────────┬───────────────────────┘
                       │ HTTP / JSON
┌──────────────────────▼───────────────────────┐
│        Python FastAPI High-Speed Backend     │
│  - Pydantic v2 validation                    │
│  - JWT Auth (Register, Login, /me)           │
│  - OpenAI GPT-4o Integration Endpoint        │
│  - Stripe Checkout & Webhook Lifecycle       │
└──────────────────────┬───────────────────────┘
                       │ SQLAlchemy Pool
┌──────────────────────▼───────────────────────┐
│        PostgreSQL 15 Container               │
│  - Synchronized via Docker Compose           │
└──────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

2. Eliminating Database Race Conditions on Cold Start

One of the most annoying bugs in Dockerized full-stack apps is FastAPI trying to query PostgreSQL before Postgres is ready to accept connections.

In database.py, we implemented a resilient startup retry loop:

def init_db(retries=5, delay=2):
    """Safely initialize database tables with retry logic on cold start."""
    for attempt in range(1, retries + 1):
        try:
            Base.metadata.create_all(bind=engine)
            print("Database connected and tables initialized.")
            return
        except Exception as e:
            print(f"Connection attempt {attempt}/{retries} failed: {e}")
            if attempt < retries:
                time.sleep(delay)
            else:
                raise e
Enter fullscreen mode Exit fullscreen mode

Coupled with Docker Compose healthcheck testing pg_isready, startup failures are completely eliminated.


3. Bulletproof Stripe Webhook Resolution

In modern Stripe Checkouts, relying on session.customer_email can fail if users pay with Apple Pay or an alternative card.

We resolved this with a dual-lookup strategy:

  1. Always pass client_reference_id=str(user.id) during session creation.
  2. In the webhook, look up by client_reference_id first.
  3. Fall back to session.customer_details.email, then session.customer_email.

This guarantees users are automatically upgraded to Premium immediately upon payment.


4. Launching AI-Flow on Product Hunt Today!

We officially launched AI-Flow on Product Hunt today!

If you are building an AI project, indie hacking, or shipping a SaaS, I would love your support and candid feedback:
Check out AI-Flow on Product Hunt & Join the Discussion


Launch Day Community Resources (20% OFF)

To celebrate launch day, here are the production-ready tools we opened up for developers:

  1. ** AI-Flow Full-Stack SaaS Boilerplate** (Next.js 14 App Router + Python FastAPI + Docker + PostgreSQL + OpenAI GPT-4o).
    • Use launch promo code PH20 for 20% OFF!
  2. ** FastAPI Production Microservices Pack** (Standalone Auth + Stripe Billing microservices, JWT, bcrypt, tested with 18 automated tests).
  3. ** AI SaaS Prompt Engineering & System Prompts Vault** (36 production-grade system prompts in structured JSON with Python integration helpers).

I would love to hear your thoughts: What is your biggest challenge when combining Next.js with Python backends? Let's discuss in the comments below!

Top comments (0)