Project Structure

Understand the directory layout and where to find and add code in nextsaas.ai Kit

Kit is delivered as a monorepo powered by Turborepo and pnpm workspaces. The main application lives in apps/boilerplate/, with shared packages in packages/. This page explains where everything lives so you know exactly where to add your own code.

Top-Level Overview

.
├── apps/
│   └── boilerplate/              # Main SaaS application (Next.js)
│       ├── prisma/               # Database schema and migrations
│       │   └── schema.prisma     # Prisma schema definition
│       ├── public/               # Static assets (favicons, images, manifests)
│       ├── src/                  # All application source code
│       │   ├── app/              # Routes, pages, layouts, and API endpoints
│       │   ├── components/       # Reusable UI components
│       │   ├── config/           # Application configuration
│       │   ├── emails/           # React Email templates
│       │   ├── hooks/            # Custom React hooks
│       │   ├── lib/              # Core business logic and utilities
│       │   ├── middleware.ts     # Request pipeline (auth + security)
│       │   ├── mocks/           # MSW API mock handlers
│       │   ├── providers/       # React context providers
│       │   └── styles/themes/   # Color theme CSS files
│       ├── e2e/                  # Playwright end-to-end tests
│       ├── .env.example          # Environment variable template
│       ├── docker-compose.yml    # Local PostgreSQL setup
│       ├── next.config.mjs       # Next.js configuration
│       ├── tailwind.config.js    # Tailwind CSS configuration
│       ├── tsconfig.json         # TypeScript configuration
│       ├── vitest.config.ts      # Unit test configuration
│       └── playwright.config.ts  # E2E test configuration
├── packages/
│   ├── ui/                       # Shared UI components (@nextsaas/ui)
│   ├── utils/                    # Shared utilities (@nextsaas/utils)
│   ├── email-templates/          # Email templates (@nextsaas/email-templates)
│   ├── blog/                     # Blog package (@nextsaas/blog)
│   ├── docs/                     # Documentation package (@nextsaas/docs)
│   └── marketing-utils/          # Marketing utilities (@nextsaas/marketing-utils)
├── package.json                  # Root workspace configuration
├── pnpm-workspace.yaml           # Workspace definitions
└── turbo.json                    # Build pipeline configuration

Shared Packages

The packages/ directory contains reusable code shared across applications. Each package is published under the @nextsaas scope and imported using scoped paths:
PackageImport PathPurpose
ui@nextsaas/ui/boilerplateShared UI components (buttons, cards, dialogs)
utils@nextsaas/utilsShared utilities (cn, formatDate, formatDateShort)
email-templates@nextsaas/email-templatesReact Email templates
blog@nextsaas/blogBlog package with MDX support
docs@nextsaas/docsDocumentation package with Markdoc support
marketing-utils@nextsaas/marketing-utilsMarketing-specific utilities
You rarely need to edit packages directly — they are consumed as dependencies by the boilerplate app.

The apps/boilerplate/src/ Directory

The apps/boilerplate/src/ directory contains all application code. Here is a breakdown of each subdirectory.

apps/boilerplate/src/app/ — Routes and Pages

Kit uses the Next.js App Router. Every folder inside apps/boilerplate/src/app/ represents a route or route group.
apps/boilerplate/src/app/
├── (auth)/           # Authentication pages (login, register)
├── (dashboard)/      # Dashboard pages (protected routes)
├── (dev)/            # Development-only pages
├── (legal)/          # Legal pages (privacy, terms, imprint)
├── api/              # API route handlers
├── logout/           # Logout flow
├── payment/          # Payment flow pages
├── layout.tsx        # Root layout (providers, fonts, theme)
├── page.tsx          # Homepage
├── globals.css       # Global styles and theme imports
├── llms.txt/         # llms.txt for AI crawlers (llmstxt.org)
├── robots.ts         # robots.txt generation
└── sitemap.ts        # sitemap.xml generation

apps/boilerplate/src/components/ — UI Components

Components are organized by feature area. Each subdirectory groups related components together.
apps/boilerplate/src/components/
├── ai/               # AI chat, image generation, and content generator components
├── auth/             # Login forms, auth guards, user menus
├── credits/          # Credit balance displays, bonus toggle, purchase flows
├── dashboard/        # Dashboard layout, sidebar, stats cards
├── demo/             # Demo mode banner and mock data UI
├── modals/           # Modal dialogs and confirmation prompts
├── payments/         # Pricing cards, checkout, billing history
├── shared/           # Cross-feature utilities (loading, errors)
├── test/             # Test-specific wrapper components
└── upload/           # File upload components

apps/boilerplate/src/lib/ — Core Logic

The lib/ directory contains all business logic, separated by domain. This is where the bulk of the application logic lives.
apps/boilerplate/src/lib/
├── ai/               # AI provider config, RAG pipeline, embeddings, image gen, content gen
├── api/              # API response helpers, error handling
├── auth/             # Auth config, test user, helpers
├── config/           # Feature flags and app constants
├── credits/          # Credit balance, consumption, tracking
├── db/               # Database client (Prisma) and query helpers
├── db.ts             # Database connection singleton
├── demo/             # Demo mode logic and mock data
├── email/            # Email sending, templates, queue
├── metadata.ts       # SEO metadata helpers
├── navigation/       # Route definitions and navigation config
├── payments/         # Lemon Squeezy integration, subscription logic
├── permissions/      # Role and permission checks
├── pricing/          # Pricing config, plan definitions, validation
├── query/            # TanStack Query keys and fetch functions
├── security/         # Rate limiting, CORS, CSP, input sanitization
├── services/         # Service layer (user, subscription, credit)
├── storage/          # Vercel Blob storage helpers
├── stores/           # Zustand client-side stores
├── utils/            # General utility functions
├── validations/      # Zod schemas for API validation
└── webhooks/         # Webhook verification and processing
The six most important directories when building features:
  • apps/boilerplate/src/lib/db/ — Database queries. Add new queries here when you need to read or write data.
  • apps/boilerplate/src/lib/api/ — API utilities. Use createApiResponse() and handleApiError() in your route handlers.
  • apps/boilerplate/src/lib/security/ — Rate limiting and validation. Apply to new API routes for production safety.
  • apps/boilerplate/src/lib/payments/ — Payment logic. Contains plan configs, checkout creation, and subscription management.
  • apps/boilerplate/src/lib/ai/ — AI integration. Provider configuration, chat logic, and the RAG pipeline.
  • apps/boilerplate/src/lib/stores/ — Zustand stores for client-side state that needs to persist across components.

apps/boilerplate/src/providers/ — Context Providers

Providers wrap the application to supply shared context. They are composed in the root layout:
src/app/layout.tsx
// Provider Hierarchy (TOP → BOTTOM):
  // 1. ClerkProvider - MUST wrap <html> and <body> (Clerk requirement)
  // 2. MSWProvider - Mock Service Worker for API interception (dev/test)
  // 3. QueryProvider - MUST be top-level for SSR/hydration safety
  // 4. ThemeProvider - Theme context (dark/light mode)
  // 5. DemoProvider - Demo mode context (passthrough when demo disabled)
  //
  // CRITICAL FIX: ClerkProvider now wraps <html> and <body> tags
  // This fixes the "useAuth can only be used within ClerkProvider" error
  // Reference: https://clerk.com/docs/nextjs/reference/components/clerk-provider
  //
  // Color Theme System:
  // - data-theme attribute applies color scheme to entire application
  // - Configured via COLOR_THEME environment variable
  // - Supports 9 themes: default, ocean, forest, sunset, midnight, coral, slate, aurora, crimson
  //
The actual root layout renders these providers around the page content:
src/app/layout.tsx
const content = (
    <html lang="en" suppressHydrationWarning data-theme={colorTheme}>
      <body className={`${inter.className} ${jetbrainsMono.variable}`}>
        <MSWProvider>
          <QueryProvider>
            <ThemeProvider
              attribute="class"
              defaultTheme="system"
              enableSystem
              disableTransitionOnChange
            >
              <DemoProvider>
                  {children}
                  <Toaster richColors position="top-center" duration={8000} />
                  {process.env.VERCEL_ENV === 'production' && <Analytics />}
                  {process.env.VERCEL_ENV === 'production' && <SpeedInsights />}
              </DemoProvider>
            </ThemeProvider>
          </QueryProvider>
        </MSWProvider>
      </body>
    </html>
  )

apps/boilerplate/src/hooks/ — Custom Hooks

Custom React hooks for accessing application state and services:
apps/boilerplate/src/hooks/
├── use-ai.ts                    # AI chat state and streaming actions
├── use-chat-rag.ts              # RAG chat with knowledge base
├── use-rag-chat.ts              # RAG chat hook with SSE streaming
├── use-image-gen.ts             # Image generation hook with session history
├── use-content-generator.ts     # Content generator hook with SSE streaming
├── use-audio-recorder.ts        # Audio recording hook (MediaRecorder API)
├── use-pricing-config.ts        # Access current pricing configuration
├── use-subscription-actions.ts  # Subscription management actions
├── use-user-tier.ts             # Current user's subscription tier
├── use-is-in-demo-mode.ts       # Check if demo mode is active
├── use-safe-query-client.ts     # Safe TanStack Query client access
└── ai-hooks.ts                  # Shared AI hook utilities

apps/boilerplate/src/styles/themes/ — Color Themes

Kit ships with 9 color themes. Each theme defines CSS custom properties for both light and dark mode:
src/styles/themes/themes.ts
export const AVAILABLE_THEMES = [
  'default',
  'ocean',
  'forest',
  'sunset',
  'midnight',
  'coral',
  'slate',
  'aurora',
  'crimson',
] as const
Switch themes by changing the COLOR_THEME environment variable. See Color Themes for details on customization.

apps/boilerplate/src/config/ — App Configuration

Central configuration for branding, SEO, and site metadata:
src/config/site.ts
export const siteConfig = {
  /** Your brand/product name */
  name: 'nextsaas.ai Kit',

  /** Short description for the homepage title tag */
  tagline: 'AI-Native Next.js SaaS Boilerplate',

  /** Name used for blog article title tags */
  blogName: 'nextsaas.ai Blog',

  /** Separator between page name and brand (En-dash is professional standard) */
  separator: '–',

  /** Base URL for metadata */
  url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000',

  /** Default description for pages without custom description */
  description:
    'Production-ready Next.js boilerplate with authentication, database, and modern UI components.',

  /** Author information */
  author: {
    name: 'Jon Doe',
    twitter: '@jondoe',
  },
} as const

export type SiteConfig = typeof siteConfig
Edit this file to change your app name, tagline, author information, and other branding details that appear across the entire application.

apps/boilerplate/src/middleware.ts — Request Pipeline

The middleware runs on every request and handles:
  1. Authentication — Clerk auth checks for protected routes
  2. Security headers — CSP, HSTS, X-Frame-Options
  3. CORS — Cross-origin request handling
See the Security Overview for details on the security middleware configuration.

Path Aliases

Kit uses a path alias so you can import from apps/boilerplate/src/ without relative path gymnastics:
tsconfig.json
"paths": {
      "@/*": ["./src/*"]
    }
This means you can write:
typescript
import { siteConfig } from '@/config/site'
import { Button } from '@/components/ui/button'
import { prisma } from '@/lib/db'
Instead of fragile relative imports like ../../../lib/db.

Key Configuration Files

FilePurpose
apps/boilerplate/next.config.mjsNext.js settings (redirects, headers, webpack)
apps/boilerplate/tailwind.config.jsTailwind CSS theme and plugin configuration
apps/boilerplate/tsconfig.jsonTypeScript compiler options and path aliases
apps/boilerplate/prisma/schema.prismaDatabase schema definition
apps/boilerplate/vitest.config.tsUnit test configuration
apps/boilerplate/playwright.config.tsE2E test configuration
apps/boilerplate/docker-compose.ymlLocal PostgreSQL and test database
apps/boilerplate/.env.exampleTemplate for environment variables
apps/boilerplate/vercel.jsonVercel deployment configuration
apps/boilerplate/postcss.config.jsPostCSS plugins (Tailwind)
apps/boilerplate/components.jsonshadcn/ui component configuration
turbo.jsonBuild pipeline configuration (root)
pnpm-workspace.yamlWorkspace definitions (root)

Where to Add Your Code

Here is a practical guide for the most common tasks:
Adding a new page:
Create a folder in apps/boilerplate/src/app/ matching your desired URL. For example, apps/boilerplate/src/app/(dashboard)/dashboard/analytics/page.tsx creates a page at /dashboard/analytics.
Adding a new component:
Place it in the appropriate apps/boilerplate/src/components/ subdirectory. If it does not fit an existing category, create a new one. Keep components focused — one component per file.
Adding business logic:
Add a new file or directory in apps/boilerplate/src/lib/. For example, apps/boilerplate/src/lib/notifications/ for a notification system. Export functions and types from an index.ts barrel file.
Adding an API route:
Create a route.ts file in apps/boilerplate/src/app/api/. For example, apps/boilerplate/src/app/api/analytics/route.ts. Use the API utilities from apps/boilerplate/src/lib/api/ and add validation with Zod schemas in apps/boilerplate/src/lib/validations/.
Adding a custom hook:
Place it in apps/boilerplate/src/hooks/ with a use- prefix. For example, apps/boilerplate/src/hooks/use-notifications.ts.