Back to Blog
·15 min
BI

BreafIO Team

Product & Engineering

Core SaaS Boilerplate: Build Your SaaS Foundation in Hours, Not Weeks

Introduction to the Core SaaS Boilerplate

Building a SaaS product from scratch is an exhilarating but daunting endeavor. Every founder and development team quickly realizes that the vast majority of time spent in the first weeks is not on the unique value proposition but on the foundational plumbing that every SaaS application needs: authentication, billing, user management, and a dashboard. The Core SaaS Boilerplate is purpose-built to eliminate this redundant work, providing a production-ready foundation that includes Google OAuth and email-password authentication, Stripe subscription billing with webhook handling, a fully functional dashboard with account settings and plan management, and one-command deployment to Vercel. In this comprehensive guide, we will explore every aspect of the Core SaaS Boilerplate, from its architecture and key features to implementation details, customization options, and deployment strategies. Whether you are a solo founder building your first SaaS, a seasoned developer looking to accelerate your next project, or a team evaluating boilerplate solutions for your organization, this guide will provide you with the deep understanding you need to make the most of the Core SaaS Boilerplate. We will cover the technology stack, the authentication flow, the billing integration, the dashboard architecture, and the deployment pipeline, giving you the confidence to build your SaaS on a solid foundation.

Why Start with a Boilerplate?

The decision to start with a boilerplate instead of building from scratch is one of the most impactful choices you can make as a SaaS founder or developer. The economics are compelling: building auth, billing, and dashboard infrastructure from scratch typically takes three to six weeks for an experienced developer, and months for a team that is learning as they go. During this time, you are not validating your product hypothesis, talking to customers, or building your core differentiator. The Core SaaS Boilerplate collapses this timeline to a single afternoon. Beyond the time savings, there is the question of correctness. Authentication systems are notoriously easy to get wrong, with subtle security issues around session management, token refresh, CSRF protection, and password hashing that can lead to devastating breaches. Stripe billing integration requires handling complex webhook event chains, idempotency keys, subscription state management, and customer portal configuration. A boilerplate that has been battle-tested across multiple projects eliminates these risks. Additionally, starting with a well-architected boilerplate establishes good patterns from day one — TypeScript types, Prisma schema conventions, API route structure, and component organization — that scale as your codebase grows. The Core SaaS Boilerplate is not just a time saver; it is a quality multiplier that let you focus on what makes your product unique.

Architecture Overview

The Core SaaS Boilerplate follows a clean, modular architecture built on Next.js 14's App Router with TypeScript throughout. The application is organized into four logical layers: the presentation layer built with React Server Components and Tailwind CSS, the API layer implemented as Next.js route handlers with input validation, the service layer containing business logic for auth, billing, and user management, and the data layer powered by Prisma ORM with PostgreSQL. The authentication layer uses Auth.js (formerly NextAuth.js) configured with both Google OAuth and email-password credentials, with sessions managed via JSON Web Tokens stored in secure HTTP-only cookies. The billing layer integrates Stripe's Checkout Sessions for initial purchases, Stripe webhooks for subscription lifecycle events, and the Stripe Customer Portal for self-serve plan management. The dashboard layer provides protected routes with middleware-based authorization, account settings with profile editing, billing status display with current plan information, and subscription management links. The deployment pipeline includes configuration for Vercel with environment variable management, database migration scripts, and a CI/CD workflow. This architecture ensures that each layer has clear responsibilities and can be extended independently without creating tight coupling between concerns.

Authentication System Deep Dive

The authentication system in the Core SaaS Boilerplate is built on Auth.js v5, which provides a unified API for multiple authentication providers while handling session management, CSRF protection, and database integration. The system supports two primary authentication methods: Google OAuth for one-click sign-in and email-password for traditional credential-based access. The Google OAuth flow uses the OAuth 2.0 authorization code grant, which is more secure than the implicit flow. When a user clicks Sign in with Google, they are redirected to Google's consent screen, and upon approval, Google issues an authorization code that the server exchanges for an access token and ID token. The email-password flow uses bcrypt for password hashing with a cost factor of 12, ensuring that even if the database is compromised, passwords remain protected. Session management uses JSON Web Tokens stored in HTTP-only, SameSite Lax cookies, which are immune to XSS attacks and have reasonable CSRF protection. The JWT contains the user ID, email, and role, encoded with an HS256 signature using a server-side secret. Token refresh is handled transparently — when a token is within 30 minutes of expiry, a new token is issued automatically. The database integration tracks users, accounts, and sessions in Prisma models, with proper indexing on email and provider account IDs for query performance. Rate limiting on the sign-in endpoint prevents brute force attacks, and email verification flows are included for the email-password provider.

Stripe Billing Integration

The Stripe billing integration is the most complex and valuable part of the Core SaaS Boilerplate. It handles the complete subscription lifecycle: product and price configuration in a central config file, Checkout Session creation with automatic tax calculation, webhook event processing for subscription creation, updates, cancellations, and payment failures, subscription status synchronization with the local database, customer portal access for self-serve plan changes, and proration handling for mid-cycle upgrades. The integration follows Stripe's recommended architecture with a dedicated webhook endpoint that verifies signatures using the webhook secret, processes events idempotently using Stripe's Idempotency-Key header, and updates the local database through Prisma transactions. The subscription state machine handles all valid transitions: trialing, active, past_due, canceled, unpaid, and incomplete. Payment failures trigger email notifications and automatic retry based on Stripe's Smart Retries feature. The billing configuration is driven by a single PLANS constant that defines all products, prices, features, and trial periods. Adding a new plan requires only adding an entry to this array — the checkout flow, webhook handling, and display logic update automatically. The Customer Portal integration uses Stripe's pre-built portal UI, configured with the allowed actions (upgrade, downgrade, cancel, update payment method) through the Stripe Dashboard.

Dashboard and User Management

The dashboard provides authenticated users with a professional interface for managing their account and subscription. It includes several key pages: the main dashboard overview showing account status, current plan, subscription details, and quick actions; the settings page for profile management including name, email, and avatar; the billing page displaying current plan, payment method, invoice history, and a link to the Stripe Customer Portal for self-serve changes; and the API keys page for programmatic access to the application. The dashboard is built with React Server Components where possible for fast initial loads, with Client Components only where interactivity is required. All dashboard routes are protected by middleware that checks for a valid session and redirects unauthenticated users to the sign-in page. User data is fetched through server-side Prisma queries, which are automatically cached and deduplicated by Next.js. The UI uses Tailwind CSS with a responsive design that works on desktop and mobile devices. The dashboard layout includes a sidebar navigation with active route highlighting, a top header with user avatar and logout button, and a responsive grid layout for content. The account settings page includes form validation, optimistic updates for a responsive feel, and confirmation dialogs for destructive actions like account deletion.

Database Schema and Prisma Integration

The Core SaaS Boilerplate uses Prisma ORM with PostgreSQL for data persistence, providing type-safe database access with auto-generated TypeScript types. The schema includes models for User, Account, Session, Subscription, and VerificationToken, following Auth.js's recommended schema structure with some enhancements. The User model includes fields for name, email, emailVerified status, image, and role. The Account model links users to OAuth provider accounts, storing provider-specific IDs and tokens. The Subscription model tracks the Stripe subscription ID, status, plan ID, current period start and end dates, and cancellation details. The schema includes proper indexes on email, provider/providedAccountId composite, and subscription status for query performance. Prisma migrations are used for schema management, with migration scripts included for initial setup and common updates. The boilerplate also includes seed scripts for development with test users and sample data. Query patterns follow best practices: select only needed fields, use include for relations, implement pagination for list queries, and use transactions for operations that modify multiple records. The database connection pool is configured for serverless deployments with connection limits appropriate for Vercel's serverless functions.

Deployment and DevOps

Deploying the Core SaaS Boilerplate to production is designed to be straightforward, with Vercel as the primary deployment target. The deployment process involves connecting your GitHub repository to Vercel, configuring environment variables through Vercel's dashboard or CLI, running database migrations as part of the build process, and setting up the Stripe webhook endpoint in the Stripe Dashboard. The boilerplate includes a vercel.json configuration file with the correct build settings, function regions, and redirects. Environment variables are documented in the .env.example file with clear descriptions of each variable's purpose. The deployment checklist covers domain configuration, SSL certificate provisioning, database connection string setup for production, Stripe webhook secret configuration, and Google OAuth credentials for the production domain. For teams using other platforms, the boilerplate is Docker-ready with a Dockerfile and docker-compose.yml for containerized deployments on Railway, Render, Fly.io, or any Docker-compatible platform. CI/CD integration is supported through GitHub Actions with workflows for linting, type checking, running tests, and deploying to preview environments on pull requests. Monitoring and error tracking can be integrated through Vercel's built-in analytics or third-party services like Sentry.

Customization and Extension

The Core SaaS Boilerplate is designed to be extended, not just used as-is. Common customizations include adding new authentication providers like GitHub, GitLab, or Magic Link, creating custom subscription plans with different feature sets, adding team or organization support on top of the single-user foundation, implementing usage-based billing alongside flat-rate subscriptions, integrating additional payment methods through Stripe, and adding admin functionality for user management and analytics. The codebase is organized to make these extensions straightforward. New auth providers are added through Auth.js's provider configuration. New plans are added to the PLANS constant. New dashboard pages follow the established pattern of server components with Prisma queries. The API route pattern provides a template for adding new endpoints with authentication, validation, and error handling. The component library using shadcn/ui provides a consistent set of UI primitives for building new features. The Prisma schema can be extended with new models and relations without breaking existing functionality. The Core SaaS Boilerplate Starter Kit includes comprehensive documentation that explains each extension point with code examples.

Getting Started with the Core SaaS Boilerplate

The fastest way to start building your SaaS on the Core SaaS Boilerplate is to purchase the starter kit and follow the setup guide. The process begins with cloning the repository and installing dependencies with npm install. Next, copy the .env.example file to .env.local and fill in your environment variables: database connection string, Stripe secret key and webhook secret, Google OAuth client ID and secret, and NEXTAUTH_SECRET for JWT encryption. Run the database migrations with npx prisma migrate dev, then seed the database with test plans using the included seed script. Start the development server with npm run dev and verify the authentication flow by signing up with Google or email-password. Test the billing flow by creating a Checkout Session and verifying the webhook processing. Deploy to Vercel following the deployment checklist. The entire process, from purchase to a working deployment, typically takes two to four hours. The starter kit also includes a comprehensive README, video walkthroughs for the key setup steps, and email support for any questions. You can have a production-ready SaaS foundation running before the end of the day.

Security Best Practices

Security is paramount in any SaaS application, and the Core SaaS Boilerplate incorporates best practices at every layer. Password hashing uses bcrypt with a cost factor of 12, making brute force attacks computationally infeasible. Session tokens are stored in HTTP-only cookies that cannot be accessed by JavaScript, eliminating XSS-based session theft. CSRF protection is handled through the SameSite cookie attribute and custom token validation for state-changing requests. API routes validate input using Zod schemas that enforce type safety and reject malformed data before it reaches the business logic. Database queries use Prisma's parameterized queries to prevent SQL injection. The Stripe integration follows PCI compliance guidelines by never handling credit card numbers directly — all payment processing happens through Stripe's hosted Checkout and Customer Portal. Environment variables for secrets are validated at application startup, and the application fails fast if required configuration is missing. Rate limiting on authentication endpoints prevents brute force attacks on login and registration. The middleware layer implements request logging for security auditing without logging sensitive data like passwords or tokens. Regular dependency updates are recommended with Dependabot configured for automated vulnerability scanning. The boilerplate also includes a security.txt file for responsible disclosure contact information, following industry standards for security research coordination.

Performance Optimization

Performance is a critical differentiator for SaaS applications, and the Core SaaS Boilerplate is optimized for fast load times and responsive interactions. The application uses Next.js App Router with React Server Components by default, which renders pages on the server and sends only the HTML to the client, eliminating the need for client-side JavaScript for initial page loads. Image optimization is handled through Next.js Image component with automatic WebP conversion, lazy loading, and responsive image sizes. Font loading uses next/font with preload hints and display swap to prevent layout shift. API responses are cached with appropriate Cache-Control headers and revalidation strategies. Database queries are optimized with selective field loading using Prisma's select and include options, avoiding SELECT * queries that fetch unnecessary data. Connection pooling is configured for PostgreSQL to handle concurrent requests efficiently. Static pages and assets are cached at the CDN level through Vercel's edge network. JavaScript bundles are automatically code-split by route, ensuring users only download the code they need for the current page. The bundle analysis tool is included for monitoring bundle sizes and identifying optimization opportunities. Lighthouse scores are consistently above 90 for performance, accessibility, and best practices. The dashboard uses optimistic UI updates for form submissions, providing immediate feedback while the server processes the request in the background.

Testing Strategy

A comprehensive testing strategy ensures the Core SaaS Boilerplate remains reliable as you extend it. The testing pyramid includes unit tests for utility functions and service logic using Vitest, integration tests for API routes that test the full request-response cycle with a test database, and end-to-end tests for critical user flows like signup, login, subscription purchase, and settings updates using Playwright. The test configuration includes a separate test database that is reset before each test suite, factory functions for creating test data with realistic defaults, and mock services for external dependencies like Stripe that are used in unit tests. The authentication flow tests verify that signup creates a user record, login sets the session cookie, protected routes redirect unauthenticated users, and token refresh works correctly. The billing flow tests verify that Checkout Session creation includes the correct price and customer data, webhook event processing creates or updates subscription records, and subscription cancellation sets the correct end date. The dashboard tests verify that the settings page loads with the current user data, profile updates persist correctly, and error states are displayed properly when API requests fail. The testing infrastructure includes continuous integration with GitHub Actions that runs all tests on every pull request and before deployment. Code coverage reports identify untested code paths, and visual regression testing catches unintended UI changes.

API Route Patterns

The Core SaaS Boilerplate establishes consistent API route patterns that make adding new endpoints straightforward while maintaining security and error handling standards. Every API route follows a structure: authentication check that validates the session token and extracts the user identity, input validation using Zod schemas that define the expected request body shape and constraints, business logic execution that implements the actual operation, error handling that catches and formats errors into a consistent JSON response structure, and response formatting that returns data in a predictable shape with proper HTTP status codes. The API routes use Next.js's Route Handlers with support for GET, POST, PUT, PATCH, and DELETE methods. Common patterns are extracted into reusable middleware functions for authentication, authorization, rate limiting, and request logging. The response format includes status, data for successful responses, error with code and message for failed responses, and metadata for paginated list responses. Error types are categorized as validation errors with field-level messages, authentication errors when the user is not logged in, authorization errors when the user lacks permissions, not found errors for missing resources, conflict errors for duplicate resources, and internal errors for unexpected failures. The API patterns are documented with OpenAPI annotations that can be used to generate API documentation automatically. Every API route includes request logging with timing information for performance monitoring.

Email Notification System

Email notifications are essential for SaaS applications, and the Core SaaS Boilerplate includes a complete email notification system. The system supports transactional emails including welcome emails after signup with getting started guide, password reset emails with secure token links, subscription confirmation emails with plan details and receipt, payment failure notification with update payment method link, subscription cancellation confirmation with reactivation option, invoice available notification with download link, and account security alerts for suspicious activity. The email system uses Resend for email delivery with React Email templates for beautiful, responsive email designs. Templates are built as React components that can be previewed in the browser during development. The email sending is handled asynchronously through background jobs to avoid blocking the API response. Failed email deliveries are retried with exponential backoff and logged for monitoring. Email preferences allow users to opt out of non-essential communications. The email configuration supports multiple environments with test mode that captures emails in a local tool instead of sending them. The template system supports dynamic content injection, conditional sections based on user attributes, and localization ready for multi-language support. All email sends are tracked with open and click rates for analytics purposes.

Ready to Build?

Get started with our production-ready starter kits and ship your project faster.

Browse Starter Kits