Launch MVP Stripe Next.js Supabase Template

repository·main·Indexed 21 days ago

https://github.com/shenseanchen/launch-mvp-stripe-nextjs-supabase

A production-ready Next.js template for rapid MVP development. It features integrated authentication via Supabase, payments via Stripe, automated email workflows using Resend and Supabase Edge Functions, and AI capabilities via OpenAI. The template includes pre-configured database triggers for user onboarding and billing, as well as Model Control Protocol (MCP) integration for AI-assisted debugging and management of Stripe and Supabase accounts.

Tokens
6.9K
Snippets
16
Records
26
Agent score
77%

What's inside launch-mvp-stripe-nextjs-supabase

  1. Understand the project structure

    main

    The project follows a standard Next.js 14 App Router structure with specialized directories for services and configuration:

    • app/: Contains the Next.js application logic, including API routes (api/email/send, api/stripe, api/user), authentication pages (auth/), and user-facing views (dashboard/, pay/, profile/).
    • components/: Reusable UI components.
    • contexts/: React Context providers for state management.
    • emails/: React Email templates.
    • hooks/: Custom React hooks.
    • services/: The service layer (e.g., emailService).
    • supabase/: Supabase-specific logic, including Edge Functions (functions/) and SQL migration scripts (scripts/setup/).
    • types/: TypeScript definitions.
    • .cursor/: Contains MCP configurations (mcp.json).
  2. Understand the Email Automation Architecture

    main

    The template uses a distributed architecture for automated transactional emails. It is critical to distinguish between environment variables used by the Next.js app (Vercel) and those used by the Supabase Edge Functions.

    • Vercel (Next.js App): Handles the UI and API routes (/api/*). It uses .env.local or Vercel Environment Variables.
    • Supabase (Database + Functions): Handles the database, triggers, and Edge Functions (Deno runtime). It uses Supabase Secrets, which are separate from Vercel environment variables.

    Email Flow:

    1. Event: User signs up (INSERT into public.users) or subscription changes.
    2. Trigger: A PostgreSQL database trigger (using pg_net) detects the change.
    3. Edge Function: The trigger calls a Supabase Edge Function.
    4. API Route: The Edge Function calls the /api/email/send route in your Next.js app.
    5. Provider: The API route uses Resend to deliver the email.
  3. Set up Resend for Email Automation

    main

    To enable transactional emails, you must configure Resend as the email provider.

    1. Create an account at resend.com and verify your domain.
    2. Generate an API key at resend.com/api-keys.
    3. Add the following keys to your .env.local file and your Vercel Project Settings:
      • RESEND_API_KEY: Your Resend API key.
      • INTERNAL_API_KEY: A random secret string used to secure communication between Edge Functions and your API.

    Verification: Ensure the key is visible in your Resend dashboard under API Keys.

    RESEND_API_KEY=re_xxxxxxxxxxxx
    INTERNAL_API_KEY=generate_a_random_secret_here
  4. Configure Stripe payments and webhooks

    main

    Follow these steps to set up Stripe for payments and subscription management:

    1. Development Mode

    • Ensure Test mode is enabled in your Stripe Dashboard.
    • Use the test card number: 4242 4242 4242 4242.
    • Create your products in the Product Catalog and set up Payment Links with trial periods if needed.

    2. Required Keys

    Map the following from your Stripe Dashboard (Test Mode) to your .env.local:

    • NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY (starts with pk_test_)
    • STRIPE_SECRET_KEY (starts with sk_test_)
    • NEXT_PUBLIC_STRIPE_BUTTON_ID (your specific Buy Button ID)

    3. Webhook Configuration

    • Add a webhook endpoint in Stripe: your_url/api/stripe/webhook.
    • Subscribe to the following events:
      • customer.subscription.*
      • checkout.session.*
      • invoice.*
      • payment_intent.*
    • Copy the Signing Secret and assign it to STRIPE_WEBHOOK_SECRET in your environment variables.
  5. Configure Supabase Database for Email Triggers

    main

    Before deploying functions, you must prepare the Supabase database by enabling the pg_net extension and creating the tracking table.

    1. Enable pg_net: Go to the Supabase SQL Editor and run:
      CREATE EXTENSION IF NOT EXISTS pg_net WITH SCHEMA extensions;
    2. Create Email Log Table: Run the contents of supabase/scripts/setup/02-create-user-email-log-table.sql in the SQL Editor to enable email tracking and prevent duplicates.

    Verification: Check the Extensions tab for pg_net (should be 'Enabled') and the Table Editor for the user_email_log table.

    CREATE EXTENSION IF NOT EXISTS pg_net WITH SCHEMA extensions;
  6. Deploy Supabase Edge Functions and Set Secrets

    main

    Edge Functions run on Supabase infrastructure and require their own environment variables (secrets) to function. Use the Supabase CLI to link your project and deploy the functions.

    1. Install and Login:
      npm install -g supabase
      supabase login
    2. Link Project:
      supabase link --project-ref YOUR_PROJECT_REF
    3. Set Secrets (Required for Edge Functions):
      supabase secrets set APP_URL=https://your-vercel-app-url.vercel.app
      supabase secrets set RESEND_API_KEY=re_your_actual_key
      supabase secrets set INTERNAL_API_KEY=your_internal_key
    4. Deploy Functions:
      supabase functions deploy send-welcome-email
      supabase functions deploy send-billing-email
      supabase functions deploy send-cancellation-email

    Verification: Check the Edge Functions tab in the Supabase Dashboard for 'Active' status.

    # Example deployment sequence
    supabase link --project-ref my-project-id
    supabase secrets set APP_URL=https://my-app.vercel.app
    supabase secrets set RESEND_API_KEY=re_123
    supabase secrets set INTERNAL_API_KEY=my_secret
    supabase functions deploy send-welcome-email
  7. Extend MCP with additional tools

    main

    You can extend your AI assistant's capabilities by adding more MCP servers to your .cursor/mcp.json. For example, you can integrate tools from the launch-mcp-demo repository (like weather or file management tools).

    1. Clone the demo repository: git clone https://github.com/ShenSeanChen/launch-mcp-demo.git.
    2. Add the new server configuration to your mcpServers object in .cursor/mcp.json, specifying the command, args (including the --directory pointing to the tool's location), and any necessary environment variables.
    3. Restart Cursor.
    {
      "mcpServers": {
        "weather": {
          "command": "/path/to/your/python/environment",
          "args": [
            "--directory",
            "/path/to/launch-mcp-demo/weather",
            "run",
            "weather.py"
          ]
        }
      }
    }
  8. Configure Supabase Authentication and Database triggers

    main

    To integrate Supabase with the template, perform the following:

    1. Authentication Setup

    • In the Supabase Dashboard, go to Authentication > Providers > Google.
    • Add your GCP Client ID and Client Secret (obtained from the Google Cloud Platform Console).
    • Update your Site URL and Redirect URLs in Supabase settings.

    2. Database Setup

    • Enable Row Level Security (RLS) for all tables.
    • Create appropriate policies for authenticated users and service roles.
    • Execute the following SQL trigger to automatically initialize user profiles, preferences, and trials when a new user authenticates via Supabase Auth:
    CREATE OR REPLACE FUNCTION public.handle_new_user()
    RETURNS trigger AS $$
    BEGIN
      INSERT INTO public.users (id, email, created_at, updated_at, is_deleted)
      VALUES (NEW.id, NEW.email, NOW(), NOW(), FALSE);
      
      INSERT INTO public.user_preferences (user_id, has_completed_onboarding)
      VALUES (NEW.id, FALSE);
      
      INSERT INTO public.user_trials (user_id, trial_start_time, trial_end_time)
      VALUES (NEW.id, NOW(), NOW() + INTERVAL '48 hours');
      
      RETURN NEW;
    END;
    $$ LANGUAGE plpgsql SECURITY DEFINER;
    
    CREATE TRIGGER on_auth_user_created
      AFTER INSERT ON auth.users
      FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
  9. Create Database Triggers for Automated Emails

    main

    To connect database events to Edge Functions, you must run specific SQL scripts in the Supabase SQL Editor. You must manually replace placeholders in the scripts before running them.

    1. User Signup Trigger:
      • Open supabase/scripts/setup/03-create-public-users-trigger.sql.
      • Replace YOUR_SUPABASE_PROJECT_REF with your actual project reference.
      • Replace YOUR_SUPABASE_ANON_KEY with your anon key (found in Project Settings → API).
      • Run the script in the SQL Editor.
    2. Billing/Cancellation Triggers:
      • Repeat the process using supabase/scripts/setup/04-create-billing-cancellation-triggers.sql.

    Verification: Check the DatabaseTriggers section in Supabase to ensure they are listed.

  10. Set up MCP (Model Control Protocol) integration

    main

    MCP enables AI assistants (like those in the Cursor editor) to interact directly with your Stripe and Supabase accounts for debugging and management.

    To set it up:

    1. Create your local configuration by copying the example: cp .cursor/mcp.json.example .cursor/mcp.json
    2. Populate the mcp.json file with your credentials:
      • Stripe: Use your Stripe API test key in the STRIPE_SECRET_KEY environment variable.
      • Supabase: Use your Supabase access token (found in Project Settings > API) as a command-line argument --access-token.
      • GitHub (Optional): Use a GitHub Personal Access Token.
    3. Security: Never commit .cursor/mcp.json to version control. It is gitignored by default.
    4. Restart your Cursor editor to apply the changes.
    {
      "mcpServers": {
        "stripe": {
          "command": "npx",
          "args": [
            "-y", 
            "@stripe/mcp"
          ],
          "env": {
            "STRIPE_SECRET_KEY": "sk_test_51ABC123..."
          }
        },
        "supabase": {
          "command": "npx",
          "args": [
            "-y",
            "@supabase/mcp-server-supabase@latest",
            "--access-token",
            "sbp_1234abcd5678efgh..."
          ]
        }
      }
    }
  11. Install and set up the Launch MVP template

    main

    To start a new project using this template, follow these steps:

    1. Clone the repository: It is recommended to clone the repo and start a fresh git history to avoid template history in your production app.
    2. Install dependencies: Run npm install or yarn install.
    3. Configure environment variables: Create a .env.local file based on the .env.example template.
    4. Configure external services: Set up Supabase, Stripe, Resend, and Google Cloud Platform (GCP) as detailed in the configuration guides.
    5. Run the development server: Use npm run dev or yarn dev and access the app at http://localhost:3000.
    # Recommended: Clone and start fresh
    git clone https://github.com/ShenSeanChen/launch-mvp-stripe-nextjs-supabase my-full-stack-app
    cd my-full-stack-app
    rm -rf .git
    git init
    git add .
    git commit -m "Initial commit from LaunchMVP template"
    git remote add origin https://github.com/YOUR_USERNAME/my-full-stack-app.git
    git push -u origin main
    
    # Install dependencies
    npm install
    
    # Start development server
    npm run dev
  12. Configure environment variables in .env.local

    main

    Create a .env.local file in your project root. You must populate the following variables from your service providers:

    Application URLs

    • NEXT_PUBLIC_APP_URL: The base URL of your application.
    • NEXT_PUBLIC_API_URL: The API endpoint URL.
    • NEXT_PUBLIC_WS_URL: The WebSocket URL.

    Supabase

    • NEXT_PUBLIC_SUPABASE_URL: Your Supabase Project URL.
    • NEXT_PUBLIC_SUPABASE_ANON_KEY: Your Supabase 'Publishable key'.
    • SUPABASE_SERVICE_ROLE_KEY: Your Supabase 'Secret key'.

    Stripe (Use TEST keys during development!)

    • NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: Your Stripe pk_test_ key.
    • NEXT_PUBLIC_STRIPE_BUTTON_ID: Your Stripe Buy Button ID.
    • STRIPE_SECRET_KEY: Your Stripe sk_test_ key.
    • STRIPE_WEBHOOK_SECRET: Your Stripe webhook signing secret (whsec_).

    Other Services

    • OPENAI_API_KEY: Your OpenAI API key.
    • RESEND_API_KEY: Your Resend API key.
    • INTERNAL_API_KEY: A custom key for internal API security.
    • NEXT_PUBLIC_POSTHOG_KEY: Your PostHog project API key.
    • NEXT_PUBLIC_POSTHOG_HOST: Your PostHog host (e.g., https://app.posthog.com).
    NEXT_PUBLIC_APP_URL=http://localhost:8000
    NEXT_PUBLIC_API_URL=http://localhost:8080
    NEXT_PUBLIC_WS_URL=ws://localhost:8080
    
    # Supabase
    NEXT_PUBLIC_SUPABASE_URL=
    NEXT_PUBLIC_SUPABASE_ANON_KEY=
    SUPABASE_SERVICE_ROLE_KEY=
    
    # OpenAI
    OPENAI_API_KEY=
    
    # Stripe
    NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_
    NEXT_PUBLIC_STRIPE_BUTTON_ID=buy_btn_
    STRIPE_SECRET_KEY=sk_test_
    STRIPE_WEBHOOK_SECRET=whsec_
    
    # Email
    RESEND_API_KEY=re_xxxxxxxxxxxx
    INTERNAL_API_KEY=your_internal_api_key
    
    # Analytics
    NEXT_PUBLIC_POSTHOG_KEY=
    NEXT_PUBLIC_POSTHOG_HOST=https://app.posthog.com