### Install Dependencies and Start Development Server
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/INDEX.md
Run these commands to install project dependencies and start the local development server.
```bash
npm install
npm run dev
```
--------------------------------
### Build and Start Production Server
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/INDEX.md
Commands to create a production build of the application and start the production server.
```bash
npm run build # Production build
npm start # Start server
```
--------------------------------
### Clone and Install SaaS Boilerplate
Source: https://github.com/ixartz/saas-boilerplate/blob/main/README.md
Clone the repository to your local environment and install all necessary dependencies.
```shell
git clone --depth=1 https://github.com/ixartz/SaaS-Boilerplate.git my-project-name
cd my-project-name
npm install
```
--------------------------------
### Example .env.local File Configuration
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/configuration.md
This snippet shows a complete example of a .env.local file, including required and optional environment variables for server-side, client-side, and third-party integrations.
```bash
# Required
CLERK_SECRET_KEY=sk_test_abc123xyz
DATABASE_URL=postgresql://user:password@localhost:5432/saas_db
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_abc123xyz
# Optional
NEXT_PUBLIC_APP_URL=https://app.example.com
NEXT_PUBLIC_LOGGING_LEVEL=debug
NEXT_PUBLIC_SENTRY_DSN=https://abc@sentry.io/123456
NODE_ENV=development
# Better Stack (optional)
NEXT_PUBLIC_BETTER_STACK_SOURCE_TOKEN=eyJhbGc...
NEXT_PUBLIC_BETTER_STACK_INGESTING_HOST=in.logs.betterstack.com
```
--------------------------------
### Create a GET API Route
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
Example of a GET API route that fetches todos for the authenticated user. It includes authentication check and database query.
```typescript
export async function GET(request: Request) {
const auth = await auth();
if (!auth.userId) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
const todos = await db.query.todoSchema.findMany({
where: eq(todoSchema.ownerId, auth.userId),
});
return Response.json(todos);
}
```
--------------------------------
### Docker Deployment Configuration
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
Dockerfile for building and running the application in a Docker container. Installs dependencies, builds the app, and starts the server.
```dockerfile
FROM node:24-alpine
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
CMD ["npm", "start"]
```
--------------------------------
### Run SaaS Boilerplate in Development Mode
Source: https://github.com/ixartz/saas-boilerplate/blob/main/README.md
Start the project locally to enable live reload and development features.
```shell
npm run dev
```
--------------------------------
### Start In-memory Local Database Server
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/configuration.md
Use this command to start the development server with an in-memory database. This is useful for build processes or CI/build testing where database persistence is not required.
```bash
npm run db-server:memory
```
--------------------------------
### Self-hosted Deployment (Node.js)
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
Build and start the application using npm. Ensure all required environment variables are set before running.
```bash
npm run build
npm start
# Set environment variables before starting
```
--------------------------------
### Start File-based Local Database Server
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/configuration.md
Use this command to start the development server with a file-based local database using pglite-server. This is the default behavior when running `npm run dev`.
```bash
npm run db-server:file
```
--------------------------------
### Install Playwright Binaries
Source: https://github.com/ixartz/saas-boilerplate/blob/main/README.md
Command to install Playwright browsers and dependencies. This is typically run once in a new environment.
```shell
npx playwright install
```
--------------------------------
### Composability Example: Pricing Section
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Demonstrates how to compose different components, such as Section, PricingCard, and Button, to create a dynamic pricing section.
```typescript
export function PricingSection() {
return (
Pricing
{AllPlans.map(plan => (
Choose Plan}
/>
))}
);
}
```
--------------------------------
### Sentry Capture Router Transition Start for Client-Side
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/LibraryModules.md
Captures router transition start events for client-side Sentry integration.
```typescript
export const onRouterTransitionStart: typeof Sentry.captureRouterTransitionStart
```
--------------------------------
### FeatureCard Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/LandingPageComponents.md
Demonstrates how to use the FeatureCard component to display feature highlights. It requires title, description, and optionally an icon.
```typescript
import { FeatureCard } from '@/features/landing/FeatureCard';
import { CheckIcon } from 'lucide-react';
export function Features() {
return (
}
title="Easy to Use"
description="Intuitive interface requires minimal setup"
/>
}
title="Powerful API"
description="Complete REST API for integration"
/>
}
title="24/7 Support"
description="Round-the-clock customer support"
/>
);
}
```
--------------------------------
### Test Production Build Locally
Source: https://github.com/ixartz/saas-boilerplate/blob/main/README.md
Starts a local server using the production build to test the generated application. Ensure CLERK_SECRET_KEY is defined in environment variables.
```shell
npm run start
```
--------------------------------
### Logger Module Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/LibraryModules.md
Demonstrates how to import and use the logger instance to log messages at different levels, including examples with context and metadata. Ensure the logger is imported from '@/libs/Logger'.
```typescript
import { logger } from '@/libs/Logger';
// Log at different levels
logger.error('Database connection failed');
logger.warning('High memory usage detected');
logger.info('User login successful');
logger.debug('Processing item', { itemId: 123 });
// With context/metadata
logger.info('Payment processed', {
orderId: 'ORD-123',
amount: 99.99,
status: 'completed',
});
```
--------------------------------
### Environment Module Usage Examples
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/LibraryModules.md
Shows how to import and access environment variables from the Environment module, including conditional logic and checking for optional variables.
```typescript
import { Env } from '@/libs/Env';
// Access environment variables
console.log(Env.NEXT_PUBLIC_APP_URL);
console.log(Env.NODE_ENV);
// In conditional logic
if (Env.NODE_ENV === 'production') {
// Production-only code
}
// Check optional variables
if (Env.NEXT_PUBLIC_BETTER_STACK_SOURCE_TOKEN) {
// Setup logging to Better Stack
}
```
--------------------------------
### Access and Use Pricing Plans
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/configuration.md
Demonstrates how to import and utilize pricing plan data. Includes examples for iterating through all plans, checking for a specific plan type, and retrieving plan-specific limits.
```typescript
import { AllPlans, PLAN_NAME } from '@/utils/PricingPlans';
// Get all plans
AllPlans.forEach(plan => {
console.log(`${plan.name}: $${plan.price}/month`);
});
// Check if plan is free
const isFree = (plan) => plan.name === PLAN_NAME.FREE;
// Get plan limits
const plan = AllPlans.find(p => p.name === PLAN_NAME.PREMIUM);
console.log(plan?.limits.teamMember); // 5
```
--------------------------------
### GET and POST Todo Route Handler
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/middleware-routing.md
Handles fetching all todos for a user via GET and creating a new todo via POST. Requires user authentication.
```typescript
import { auth } from '@clerk/nextjs/server';
import { db } from '@/libs/DB';
import { todoSchema } from '@/models/Schema';
export async function GET(request: Request) {
const { userId } = await auth();
if (!userId) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
const todos = await db.query.todoSchema.findMany({
where: eq(todoSchema.ownerId, userId),
});
return Response.json(todos);
}
export async function POST(request: Request) {
const { userId } = await auth();
const { title, message } = await request.json();
if (!userId) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
const todo = await db.insert(todoSchema).values({
title,
message,
ownerId: userId,
}).returning();
return Response.json(todo[0], { status: 201 });
}
```
--------------------------------
### Example Usage of Badge Variants
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Demonstrates how to use the Badge component with different predefined variants to display status information.
```typescript
import { Badge } from '@/components/ui/badge';
export function StatusBadges() {
return (
ActivePendingErrorInfo
);
}
```
--------------------------------
### DashboardHeader Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/DashboardComponents.md
Example of how to use the DashboardHeader component within a dashboard layout, passing navigation menu items.
```typescript
import { DashboardHeader } from '@/features/dashboard/DashboardHeader';
export function DashboardLayout({ children }: { children: React.ReactNode }) {
const locale = useLocale();
const menu = [
{ href: '/dashboard', label: 'Overview' },
{ href: '/dashboard/settings', label: 'Settings' },
{ href: '/dashboard/team', label: 'Team' },
];
return (
{children}
);
}
```
--------------------------------
### FAQ Template Usage
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Example of integrating the FAQ template component into a landing page. It is often used after the Features section.
```typescript
import { FAQ } from '@/templates/FAQ';
export function LandingPage() {
return (
<>
{/* Other sections */}
>
);
}
```
--------------------------------
### AppLocale Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/types.md
Demonstrates how to access and iterate over configured application locales using the AppLocale type. Ensure AppConfig.i18n.locales is properly set up.
```typescript
import type { AppLocale } from '@/types/I18n';
import { AppConfig } from '@/utils/AppConfig';
// Access configured locales
const locales: AppLocale[] = AppConfig.i18n.locales;
locales.forEach(locale => {
console.log(`${locale.id}: ${locale.name}`);
// en: English
// fr: Français
});
```
--------------------------------
### AppConfig Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/configuration.md
Demonstrates how to import and access various configuration values from the `AppConfig` object, such as the application name, locales, and support email. This is useful for dynamically configuring application behavior.
```typescript
import { AppConfig } from '@/utils/AppConfig';
// Access app name
console.log(AppConfig.name); // 'SaaS Template'
// List available locales
AppConfig.i18n.locales.forEach(locale => {
console.log(`${locale.id}: ${locale.name}`);
});
// Get support email
console.log(AppConfig.email.support);
// contact@nextjs-boilerplate.com
// Check locale configuration
const isDefaultLocale = (locale: string) =>
locale === AppConfig.i18n.defaultLocale;
```
--------------------------------
### Database Module Usage Examples
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/LibraryModules.md
Demonstrates common database operations like querying, inserting, updating, and deleting data using the Drizzle ORM instance.
```typescript
import { db } from '@/libs/DB';
// Query data
const todos = await db.query.todoSchema.findMany();
// Insert data
await db.insert(todoSchema).values({
title: 'My Task',
message: 'Task description',
ownerId: userId,
});
// Update data
await db
.update(todoSchema)
.set({ title: 'Updated' })
.where(eq(todoSchema.id, id));
// Delete data
await db
.delete(todoSchema)
.where(eq(todoSchema.id, id));
```
--------------------------------
### Protected Page Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/INDEX.md
Demonstrates how to protect a Next.js page using Clerk authentication, redirecting unauthenticated users to the sign-in page.
```typescript
import { auth } from '@clerk/nextjs/server';
import { redirect } from 'next/navigation';
export default async function ProtectedPage() {
const { userId } = await auth();
if (!userId) redirect('/sign-in');
return
Protected content
;
}
```
--------------------------------
### Separator Component Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Illustrates the usage of the Separator component to create visual dividers. This example uses vertical separators within a navigation layout. Ensure the Separator component is imported.
```typescript
import { Separator } from '@/components/ui/separator';
export function Navigation() {
return (
);
}
```
--------------------------------
### Dropdown Menu Component Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Shows how to implement a Dropdown Menu for user interactions. Requires importing DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, and DropdownMenuItem. The DropdownMenuTrigger can use 'asChild' for custom button rendering.
```typescript
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
} from '@/components/ui/dropdown-menu';
export function UserMenu() {
return (
ProfileSettingsSign Out
);
}
```
--------------------------------
### Accordion Component Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Demonstrates how to use the Accordion component for organizing collapsible content sections. Ensure Accordion, AccordionItem, AccordionTrigger, and AccordionContent are imported.
```typescript
import {
Accordion,
AccordionItem,
AccordionTrigger,
AccordionContent,
} from '@/components/ui/accordion';
export function FAQSection() {
return (
Is it accessible?
Yes, it adheres to the WAI-ARIA design pattern.
);
}
```
--------------------------------
### Button Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/UIComponents.md
Demonstrates various ways to use the Button component, including different variants, sizes, icon buttons, custom classes, event handlers, disabled states, and using as an anchor element.
```typescript
import { Button } from '@/components/ui/button';
export function ButtonDemo() {
return (
{/* Default variant with size */}
{/* Different variants */}
{/* Icon buttons */}
{/* With custom className */}
{/* With onClick handler */}
{/* Disabled state */}
{/* As anchor via asChild */}
);
}
```
--------------------------------
### Server Component Example with Auth and DB Access
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
This server component demonstrates accessing authentication context from Clerk and querying the database using Drizzle. It's suitable for server-side data fetching and logic.
```typescript
// Server component (default)
export default async function Page() {
// Can access:
// - auth() from Clerk
// - db from Drizzle
// - Direct database queries
// - Server-only secrets
const auth = await auth();
const data = await db.query.todoSchema.findMany();
return ;
}
```
--------------------------------
### DemoBanner Template Usage
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Example of how to include the DemoBanner template component on a landing page. It is typically placed at the top, before other content.
```typescript
import { DemoBanner } from '@/templates/DemoBanner';
export function LandingPage() {
return (
<>
{/* Page content */}
>
);
}
```
--------------------------------
### LogoCloud Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/LandingPageComponents.md
Shows how to implement the LogoCloud component to display a grid of company logos. It accepts an array of logo objects, each with a name and a logo element, and an optional title.
```typescript
import { LogoCloud } from '@/features/landing/LogoCloud';
export function TrustedBy() {
return (
},
{ name: 'Company B', logo: },
{ name: 'Company C', logo: },
]}
/>
);
}
```
--------------------------------
### PricingFeatureItem Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/BillingComponents.md
Demonstrates how to use the PricingFeatureItem component to display various plan features within an unordered list. Ensure the parent element provides appropriate spacing.
```typescript
import { PricingFeatureItem } from '@/features/billing/PricingFeatureItem';
export function CustomFeatureList() {
return (
);
}
```
--------------------------------
### Features Template Usage
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Example of how to use the Features template component within a landing page structure. It is typically placed after a hero section.
```typescript
import { Features } from '@/templates/Features';
export function LandingPage() {
return (
<>
{/* Other sections */}
>
);
}
```
--------------------------------
### Next.js App Router Directory Structure
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/middleware-routing.md
Illustrates the file system-based routing structure for an Next.js application using the App Router. It shows how directories map to URL paths and includes examples of locale-based routing, route groups for authentication and marketing pages, and dynamic segments for optional catch-all routes.
```tree
src/app/
├── [locale]/
│ ├── page.tsx # / or /:locale/
│ ├── layout.tsx # Layout for locale routes
│ ├── (auth)/
│ │ ├── layout.tsx # Auth layout (centered)
│ │ ├── (center)/
│ │ │ ├── layout.tsx # Center auth container
│ │ │ ├── sign-in/
│ │ │ │ └── [[...sign-in]]/
│ │ │ │ └── page.tsx # Clerk sign-in page
│ │ │ └── sign-up/
│ │ │ └── [[...sign-up]]/
│ │ │ └── page.tsx # Clerk sign-up page
│ │ ├── dashboard/
│ │ │ ├── layout.tsx # Dashboard layout
│ │ │ ├── page.tsx # Dashboard home
│ │ │ ├── organization-profile/
│ │ │ │ └── page.tsx # Org settings (Clerk)
│ │ │ └── user-profile/
│ │ │ └── page.tsx # User settings (Clerk)
│ │ └── onboarding/
│ │ └── organization-selection/
│ │ └── page.tsx # Select/create org
│ │
│ └── (marketing)/
│ └── page.tsx # Landing page
│
├── global-error.tsx # Global error boundary
├── robots.ts # SEO robots.txt
└── sitemap.ts # SEO sitemap.xml
```
--------------------------------
### Client Component Example with i18n and State
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
This client component shows how to use hooks from next-intl for routing and translations, along with standard React hooks like useState and useEffect. It's designed for interactive UI elements.
```typescript
// Client component (marked with 'use client')
'use client';
export function ClientComponent({ data }) {
// Can access:
// - useRouter, usePathname from next-intl
// - useLocale, useTranslations from next-intl
// - useState, useEffect
const router = useRouter();
const t = useTranslations();
return ;
}
```
--------------------------------
### Set up Clerk Authentication Environment Variables
Source: https://github.com/ixartz/saas-boilerplate/blob/main/README.md
Configure your .env.local file with Clerk publishable and secret keys for authentication.
```shell
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_clerk_pub_key
CLERK_SECRET_KEY=your_clerk_secret_key
```
--------------------------------
### Run Database Migration
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
Execute this command to apply pending database migrations.
```bash
npm run db:migrate
```
--------------------------------
### Deploy to Vercel
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
Use the Vercel CLI to deploy the application. Environment variables should be configured in the Vercel dashboard.
```bash
vercel deploy
# Environment variables configured in Vercel dashboard
```
--------------------------------
### Create Navigation Instance
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/middleware-routing.md
Initializes the navigation instance with routing configuration.
```typescript
export const { Link, usePathname, useRouter } = createNavigation(routing);
```
--------------------------------
### Check Authorization Role in Component
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
Example of how to check a user's authorization role within a component to conditionally render content.
```typescript
if (role === ORG_ROLE.ADMIN) { ... }
```
--------------------------------
### Open Database Studio
Source: https://github.com/ixartz/saas-boilerplate/blob/main/README.md
Opens Drizzle Studio to explore the database. Access it via https://local.drizzle.studio in your browser.
```shell
npm run db:studio
```
--------------------------------
### Project File Structure
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/README.md
This snippet displays the directory structure of the SaaS Boilerplate project, indicating the location of various documentation files and API reference components.
```bash
```
/workspace/home/output/
├── README.md # This file
├── INDEX.md # Navigation & quick reference
├── overview.md # Architecture & design
├── types.md # Type definitions
├── configuration.md # Config & environment
├── errors.md # Error handling
├── middleware-routing.md # Routing & auth flow
│
└── api-reference/ # Component APIs
├── Utilities.md
├── Hooks.md
├── UIComponents.md
├── DashboardComponents.md
├── LandingPageComponents.md
├── BillingComponents.md
├── FeatureComponents.md
└── LibraryModules.md
```
```
--------------------------------
### TypeScript Type Error Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/errors.md
Demonstrates a type error when assigning an incorrect string to a typed property and its resolution using a type-safe enum.
```typescript
// ❌ Error: Type 'string' is not assignable to type 'PlanName'
const plan: PricingPlan = {
name: 'invalid', // Type error - must be 'free' | 'premium' | 'enterprise'
price: 0,
limits: { ... }
};
// ✅ Fixed
const plan: PricingPlan = {
name: PLAN_NAME.FREE, // Type-safe enum value
price: 0,
limits: { ... }
};
```
--------------------------------
### SaaS Boilerplate Directory Structure
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
Provides a detailed breakdown of the project's directory layout, outlining the purpose of each folder.
```text
src/
├── app/ # Next.js pages and route handlers
│ ├── [locale]/ # Dynamic locale segments
│ ├── (auth)/ # Protected routes group
│ ├── (marketing)/ # Public marketing routes
│ └── global-error.tsx # Global error boundary
├── components/ # Reusable UI components
│ ├── ui/ # Shadcn UI primitives
│ ├── ActiveLink.tsx # Navigation component
│ ├── LocaleSwitcher.tsx # Locale selector
│ └── ...
├── features/ # Feature-specific components
│ ├── billing/ # Pricing components
│ ├── dashboard/ # Dashboard layout components
│ ├── landing/ # Landing page sections
│ └── sponsors/ # Sponsor display
├── hooks/ # React hooks
│ └── UseMenu.ts # Menu state management
├── libs/ # Core libraries
│ ├── DB.ts # Database connection
│ ├── Env.ts # Environment validation
│ ├── Logger.ts # Structured logging
│ ├── I18n.ts # Localization config
│ ├── I18nRouting.ts # i18n routing
│ └── I18nNavigation.ts # Locale-aware navigation
├── models/ # Database schema
│ └── Schema.ts # Drizzle ORM schema
├── types/ # TypeScript type definitions
│ ├── Auth.ts # Authorization types
│ ├── I18n.ts # Localization types
│ ├── Subscription.ts # Billing types
│ └── Enum.ts # Type utilities
├── utils/ # Utility functions
│ ├── AppConfig.ts # App configuration
│ ├── Helpers.ts # Helper functions (cn, getBaseUrl, getI18nPath)
│ ├── DBConnection.ts # Database connection factory
│ └── PricingPlans.ts # Pricing configuration
├── locales/ # Translation files
│ ├── en.json # English translations
│ └── fr.json # French translations
├── styles/ # Global styles
│ └── globals.css # Tailwind CSS
├── templates/ # Reusable page templates
│ ├── Logo.tsx # App logo
│ ├── Features.tsx # Features section
│ ├── FAQ.tsx # FAQ section
│ ├── CTA.tsx # Call-to-action template
│ └── DemoBanner.tsx # Demo banner
├── instrumentation.ts # Server-side Sentry setup
├── instrumentation-client.ts # Client-side Sentry setup
└── proxy.ts # Request middleware (auth + i18n)
```
--------------------------------
### Routing Configuration
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/middleware-routing.md
Defines the routing configuration with supported locales, locale prefix strategy, and the default locale. This setup is essential for managing multi-language support in the application.
```typescript
export const routing = defineRouting({
locales: AllLocales, // ['en', 'fr']
localePrefix: AppConfig.i18n.localePrefix, // 'as-needed'
defaultLocale: AppConfig.i18n.defaultLocale, // 'en'
});
```
--------------------------------
### Header Component with OrganizationMenu
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/DashboardComponents.md
Example of how to use the OrganizationMenu component within a Header component. It's typically placed alongside other dashboard elements like Logo and UserMenu.
```typescript
import { OrganizationMenu } from '@/features/dashboard/OrganizationMenu';
export function Header() {
return (
);
}
```
--------------------------------
### Database Management Commands
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/INDEX.md
Commands for generating migrations, applying them to the database, and inspecting the database schema.
```bash
npm run db:generate # Generate migration
npm run db:migrate # Apply migration
npm run db:studio # Inspect database
```
--------------------------------
### usePathname Hook for Current Path
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/middleware-routing.md
Demonstrates the use of the usePathname hook to get the current URL path without the locale prefix. This is useful for active link highlighting.
```typescript
import { usePathname } from '@/libs/I18nNavigation';
const pathname = usePathname();
// Returns path without locale prefix
// - In English (/dashboard): '/dashboard'
// - In French (/fr/dashboard): '/dashboard'
```
```typescript
'use client';
import { usePathname } from '@/libs/I18nNavigation';
import { cn } from '@/utils/Helpers';
export function NavLink({ href, label }: { href: string; label: string }) {
const pathname = usePathname();
const isActive = pathname.endsWith(href);
return (
{label}
);
}
```
--------------------------------
### Generate Production Build
Source: https://github.com/ixartz/saas-boilerplate/blob/main/README.md
Generates an optimized production build of the boilerplate. Ensure DATABASE_URL is defined in environment variables.
```shell
npm run build
```
--------------------------------
### Section
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/LandingPageComponents.md
A reusable section wrapper component for organizing landing page content with consistent spacing and layout.
```APIDOC
## Section
### Description
A reusable section wrapper component for organizing landing page content with consistent spacing and layout.
### Signature
```typescript
export const Section = (props: {
children: React.ReactNode;
className?: string;
}): JSX.Element
```
### Parameters
#### Path Parameters
* None
#### Query Parameters
* None
#### Request Body
* None
### Parameters
- **children** (React.ReactNode) - Required - Section content
- **className** (string) - Optional - Optional additional CSS classes
### Return Value
Returns a section wrapper with responsive padding and max-width constraints.
### Request Example
```typescript
import { Section } from '@/features/landing/Section';
import { FeatureCard } from '@/features/landing/FeatureCard';
export function FeaturesSection() {
return (
Features
);
}
```
```
--------------------------------
### EnumValues Usage Example
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/types.md
Illustrates how to use the EnumValues utility type to derive a union type from a const enumeration. The resulting type ensures that only valid enum values can be passed to functions.
```typescript
import type { EnumValues } from '@/types/Enum';
const MY_ENUM = {
FIRST: 'first',
SECOND: 'second',
THIRD: 'third',
} as const;
// Automatically creates the union type
type MyEnumValue = EnumValues;
// Equivalent to: 'first' | 'second' | 'third'
function processValue(val: MyEnumValue) {
// Type checker only allows values from MY_ENUM
}
```
--------------------------------
### Handle Drizzle ORM Query Errors
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/errors.md
Query errors throw exceptions that propagate to error boundaries. This example shows how to handle 'row not found' and other query exceptions using try-catch.
```typescript
import { db } from '@/libs/DB';
import { todoSchema } from '@/models/Schema';
try {
const todo = await db.query.todoSchema.findFirst({
where: eq(todoSchema.id, id),
});
if (!todo) {
// Handle not found
return notFound();
}
return todo;
} catch (error) {
logger.error('Query failed', { error });
return { error: 'Database query failed' };
}
```
--------------------------------
### Using ActiveLink in a Navigation Menu
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/UIComponents.md
Demonstrates how to use the ActiveLink component within a navigation menu to create interactive links. Ensure the 'use client' directive is present in the file.
```typescript
import { ActiveLink } from '@/components/ActiveLink';
export function DashboardMenu() {
return (
);
}
```
--------------------------------
### Render PricingCard for Multiple Plans
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/BillingComponents.md
Demonstrates how to use the PricingCard component to display different subscription plans. It maps over an array of plans and renders a PricingCard for each, passing the plan details and a dynamically styled button.
```typescript
import { PricingCard } from '@/features/billing/PricingCard';
import { Button } from '@/components/ui/button';
import { AllPlans } from '@/utils/PricingPlans';
export function PricingPage() {
return (
{AllPlans.map(plan => (
Get Started
}
/>
))}
);
}
```
--------------------------------
### Register Sentry for Server-Side
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/LibraryModules.md
Initializes Sentry for Node.js or Edge runtime. Next.js automatically calls this on startup.
```typescript
export function register(): void
export const onRequestError: typeof Sentry.captureRequestError
```
```typescript
import { register, onRequestError } from '@/instrumentation';
export function middleware() {
// Error handling is automatic via onRequestError
}
```
--------------------------------
### Run Unit Tests with Vitest
Source: https://github.com/ixartz/saas-boilerplate/blob/main/README.md
Command to execute all unit tests using Vitest. Tests are located alongside the source code.
```shell
npm run test
```
--------------------------------
### Get Application Base URL with getBaseUrl
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/Utilities.md
Retrieve the application's public base URL, defaulting to `http://localhost:3000` if the `NEXT_PUBLIC_APP_URL` environment variable is not set. Useful for constructing absolute URLs for API requests or share links.
```typescript
import { getBaseUrl } from '@/utils/Helpers';
// In development (no NEXT_PUBLIC_APP_URL set)
const devUrl = getBaseUrl(); // 'http://localhost:3000'
// In production (NEXT_PUBLIC_APP_URL='https://example.com')
const prodUrl = getBaseUrl(); // 'https://example.com'
// Use in API calls
async function fetchUser(userId: string) {
const baseUrl = getBaseUrl();
const response = await fetch(`${baseUrl}/api/users/${userId}`);
return response.json();
}
// Use for constructing full URLs
export function generateShareLink(itemId: string) {
const baseUrl = getBaseUrl();
return `${baseUrl}/share/${itemId}`;
}
```
--------------------------------
### Generate Build Statistics
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/configuration.md
Run this command to generate bundle analysis statistics for your project. This helps in identifying large dependencies and optimizing the build.
```bash
npm run build-stats
```
--------------------------------
### Badge Component Usage
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/UIComponents.md
Demonstrates various ways to use the Badge component, including different variants, with icons, and as links. Ensure the Badge component and its associated styles are imported.
```typescript
import { Badge } from '@/components/ui/badge';
export function BadgeDemo() {
return (
DefaultSecondaryErrorOutline
{/* With icons */}
Verified
{/* As links */}
JavaScript
);
}
```
--------------------------------
### Database Migration Commands
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/configuration.md
Manage database migrations using these commands. Generate migrations from schema changes, apply pending migrations, or open Drizzle Studio for inspection.
```bash
npm run db:generate # Generate migration from schema changes
```
```bash
npm run db:migrate # Apply pending migrations
```
```bash
npm run db:studio # Open Drizzle Studio for database inspection
```
--------------------------------
### Landing Page Structure with Feature Components
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/FeatureComponents.md
Illustrates the overall structure of a landing page, integrating various feature components like hero, sections, logo clouds, CTA banners, and footers.
```typescript
import { CenteredHero } from '@/features/landing/CenteredHero';
import { Section } from '@/features/landing/Section';
import { FeatureCard } from '@/features/landing/FeatureCard';
import { LogoCloud } from '@/features/landing/LogoCloud';
import { CTABanner } from '@/features/landing/CTABanner';
import { CenteredFooter } from '@/features/landing/CenteredFooter';
import { Button } from '@/components/ui/button';
export default function LandingPage() {
return (
{/* Hero Section */}
Get Started}
/>
{/* Features Section */}
);
}
```
--------------------------------
### Generate Database Migration
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/overview.md
Use this command to generate a new database migration file after updating the schema.
```bash
npm run db:generate
```
--------------------------------
### Log Levels and Visibility Table
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/errors.md
This table outlines different log levels, their use cases, and their default visibility. To enable detailed logs, set the NEXT_PUBLIC_LOGGING_LEVEL environment variable to 'debug' or 'trace'.
```markdown
LEVEL | USE CASE | DEFAULT VISIBLE
---------|------------------------------------|-----------------
fatal | Application cannot continue | Always
error | Recoverable errors | Always
warning | Suspicious behavior | Yes
info | General information (default) | Yes
debug | Debugging information | When LEVEL=debug
trace | Very detailed trace | When LEVEL=trace
```
--------------------------------
### MobileNavigation Component Usage
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/api-reference/DashboardComponents.md
Demonstrates how to use the MobileNavigation component with a predefined menu. This component is intended for use on small screens.
```typescript
import { MobileNavigation } from '@/features/dashboard/MobileNavigation';
const dashboardMenu = [
{ href: '/dashboard', label: 'Dashboard' },
{ href: '/dashboard/team', label: 'Team' },
];
export function Header() {
return (
);
}
```
--------------------------------
### Import Paths for SaaS Boilerplate
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/INDEX.md
Lists common import paths for libraries, utilities, hooks, UI components, dashboard features, landing page components, types, and schema definitions within the SaaS boilerplate.
```typescript
// Libraries
import { db } from '@/libs/DB';
import { Env } from '@/libs/Env';
import { logger } from '@/libs/Logger';
import { routing } from '@/libs/I18nRouting';
import { Link, usePathname, useRouter } from '@/libs/I18nNavigation';
// Utilities
import { cn, getBaseUrl, getI18nPath } from '@/utils/Helpers';
import { AppConfig } from '@/utils/AppConfig';
import { AllPlans, PLAN_NAME } from '@/utils/PricingPlans';
// Hooks
import { useMenu } from '@/hooks/UseMenu';
// UI Components
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LocaleSwitcher } from '@/components/LocaleSwitcher';
import { ActiveLink } from '@/components/ActiveLink';
// Dashboard
import { DashboardHeader } from '@/features/dashboard/DashboardHeader';
import { OrganizationMenu } from '@/features/dashboard/OrganizationMenu';
// Landing
import { CenteredHero } from '@/features/landing/CenteredHero';
import { Section } from '@/features/landing/Section';
import { FeatureCard } from '@/features/landing/FeatureCard';
// Types
import type { OrgRole } from '@/types/Auth';
import type { PricingPlan } from '@/types/Subscription';
import type { AppLocale } from '@/types/I18n';
// Schema
import { todoSchema } from '@/models/Schema';
```
--------------------------------
### Environment Configuration with Defaults
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/errors.md
Shows how to access environment variables with fallback default values in a Next.js application. It illustrates optional variables and conditional feature flags.
```typescript
import { Env } from '@/libs/Env';
// Optional env var with fallback
const appUrl = Env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3000';
// Conditional features
if (Env.NEXT_PUBLIC_BETTER_STACK_SOURCE_TOKEN) {
// Better Stack logging enabled
}
// Log level configuration
const logLevel = Env.NEXT_PUBLIC_LOGGING_LEVEL ?? 'info';
```
--------------------------------
### Configure PostCSS Plugins
Source: https://github.com/ixartz/saas-boilerplate/blob/main/_autodocs/configuration.md
Defines the PostCSS plugins to be used. Currently configured to use Tailwind CSS.
```javascript
{
"plugins": {
"@tailwindcss/postcss": {}
}
}
```