NextDevKit Project Architecture
A comprehensive guide to understanding NextDevKit's project structure, from basic Next.js setup to production-ready SaaS architecture.
This guide will help you understand how NextDevKit is organized by showing the evolution from a basic Next.js project to a complete production-ready SaaS template. Each step builds upon the previous one, making it easy to understand the rationale behind every architectural decision.
Understanding the Evolution
NextDevKit is designed as a production-ready starter template, which means it includes many features from day one. However, understanding how this structure evolved helps you:
- Navigate the codebase with confidence
- Extend features following established patterns
- Make architectural decisions aligned with the project
- Onboard new developers efficiently
Let's start from the beginning and build up to the complete architecture.
Step 1: Foundation - Next.js Basics
Every Next.js project starts with these essential files. This is the minimal setup you need to run a Next.js application.
Key Files:
layout.tsx
- Root layout wrapping all pages (global header, footer, metadata)page.tsx
- The homepage at/
globals.css
- Global styles and Tailwind directivesnext.config.ts
- Next.js configurationtsconfig.json
- TypeScript configuration
Step 2: Adding Essential Tools
Before building features, we add development tools and styling foundations that ensure code quality and consistency.
We can run the following command to add more needed shadcn/ui base components:
pnpm dlx shadcn@latest add button input card
What's Added:
components/ui/
- shadcn/ui components (design system primitives)lib/utils.ts
- Utility functions (cn helper, formatters, etc.)biome.json
- Code formatting and linting configurationcomponents.json
- shadcn/ui configurationpostcss.config.mjs
- PostCSS configuration for Tailwind
Step 3: Organizing Routes with App Router
As the application grows, we organize routes using Next.js App Router patterns: route groups and internationalization.
Architecture Patterns:
[locale]/
- Dynamic segment for internationalization (e.g.,/en
,/zh
)(marketing)/
- Route group for public pages (doesn't affect URL)(app)/
- Route group for authenticated pages[[...slug]]
- Optional catch-all for flexible routing (docs)[...slug]
- Required catch-all for blog posts and legal pages
URL Examples:
/en/pricing
→ English pricing page/zh/blog/nextdevkit-tech-stack
→ Chinese blog post/en/docs/getting-started/overview
→ Documentation page/en/credits
→ Credits pricing page/auth/login
→ Login page (no locale needed)/app/dashboard
→ Dashboard (protected route)/app/admin/users
→ Admin users page/app/ai/chat
→ AI chat feature
Step 4: Component Architecture
In addition to page routing, we also need to organize frontend component style files so we can better reuse these frontend components. All reusable frontend components are placed in the src/components/
directory.
Frontend Component Organization:
ui/
- Primitive, reusable UI components from shadcn/ui (More shadcn/ui components...)auth/
- Authentication forms and componentsmarketing/
- Landing page and marketing components organized by featuredashboard/
- Application dashboard layout component examplessettings/
- User settings forms organized by category (account, billing, notification, security, usage)admin/
- Admin panel componentsai-elements/
- Vercel AI SDK related UI components (conversation, message, code-block, etc.)shared/
- Shared across multiple features (header, footer, cookie, etc.)docs/
&blog/
- MDX content componentsexamples/
- Example implementations (AI chat, AI image generation, dashboard examples)icons/
- Logo, social media, and tech stack icons
Step 5: Content Management
MDX-based content management makes the APP easy to customize and maintain. Use MDX to build blog and documentation with internationalization support. All content is placed in the src/content/
directory.
Configuration Structure:
content/
- MDX content for blog (8 posts), docs, and legal pagesi18n/
- Internationalization utilitiesmessages/
- Translation files (English and Chinese)
Step 6: Database and Authentication
The data layer and authentication system form the backbone of the application. You need to be familiar with Drizzle ORM and Better Auth usage to build your database and authentication system.
Database client and corresponding tables are placed in the src/database/
directory. Authentication related files are placed in the src/lib/auth/
directory.
Database Layer:
database/client.ts
- Drizzle ORM client instancedatabase/schema.ts
- Database tables and relations (users, sessions, credits, transactions, etc.)drizzle/
- Migration files and history
Authentication System:
lib/auth.ts
- Better Auth configurationlib/auth/client.ts
- Client-side auth utilities (useSession
,reloadSession
)lib/auth/server.ts
- Server-side auth utilities (getSession
)lib/auth/api.ts
- API route helperslib/auth/edge.ts
- Edge runtime helperslib/auth/session-context.ts
- React context for sessionlib/auth/errors.ts
- Auth error handling
Supporting Libraries:
lib/actions/
- Server actions for data mutationslib/hooks/
- Custom React hookslib/stores/
- Zustand stores for global statelib/safe-action.ts
- Type-safe server action wrapperlib/source.ts
- Fumadocs source configurationtypes/
- Shared TypeScript type definitions
Step 7: API Routes and Server Functions
Backend functionality is implemented through API routes and server actions. You need to be familiar with Next.js API routes, you can create new /api/**/route.ts
to implement your API routes.
API Routes:
api/auth/[...all]/route.ts
- Better Auth API handler (catch-all route)api/ai/demo/chat/route.ts
- AI chat demo endpointapi/ai/demo/image/route.ts
- AI image generation demo endpointapi/search/route.ts
- Documentation search functionalityapi/jobs/credits/expire/route.ts
- Cron job to expire creditsapi/jobs/credits/grant/route.ts
- Cron job to grant subscription creditsapi/webhooks/stripe/route.ts
- Stripe webhook handlerapi/webhooks/creem/route.ts
- Creem webhook handler
Special Routes:
image-proxy/[...path]/route.ts
- Image proxy for optimizationrobots.ts
- Dynamic robots.txt generationsitemap.ts
- Dynamic sitemap generation
Middleware:
middleware.ts
- Route protection, redirects, internationalization
Step 8: Business Logic Modules
Enterprise features like AI, credits, payments, email, and storage are organized as modular systems. You need to be familiar with these modules usage to build your business logic.
ai/
- AI related files are placed insrc/ai/
directory.credits/
- Credits related files are placed insrc/credits/
directory.payment/
- Payment related files are placed insrc/payment/
directory.mail/
- Mail related files are placed insrc/mail/
directory.storage/
- Storage related files are placed insrc/storage/
directory.
AI System:
ai/models/
- AI model configurations (chat, image)ai/agents/
- AI agents and tools (weather agent)ai/image/
- Image generation utilities and hooksai/prompts.ts
- System prompts and templatesai/errors.ts
- AI-specific error handling
Credits System:
credits/actions/
- Server actions for credits management (10+ action files)- Consume, grant, expire credits
- Track user transactions
- Handle subscription and purchase bonuses
credits/types.ts
- Credits-related TypeScript types
Payment System:
payment/actions/
- Server actions for payment operations (10 action files)- Create checkout links and customer portals
- Handle subscriptions and one-time payments
- Process webhooks from payment providers
payment/providers/
- Payment provider implementations (Stripe, Creem)payment/types.ts
- Payment-related TypeScript types
Email System:
mail/providers/resend.ts
- Resend email service integrationmail/templates/
- React Email templatesmail/components/
- Reusable email components (button, layout)mail/actions.ts
- Newsletter subscriptions, email sending
Storage System:
storage/providers/s3.ts
- AWS S3 storage integrationstorage/actions.ts
- File upload, signed URLs
Provider Pattern Benefits:
- Easy to add new providers by implementing the same interface
- Test with mock providers
- Support multiple payment providers simultaneously (Stripe + Creem)
- Consistent API across different services
Step 9: Complete Production Architecture
The final architecture includes all pieces working together for a production-ready SaaS application.
Architecture Principles
NextDevKit follows these core principles to maintain quality and scalability:
1. Separation of Concerns
Presentation Layer (components/
):
- UI components that render interfaces
- No direct database or business logic
- Use hooks and actions for data
Business Logic Layer (ai/
, credits/
, payment/
, mail/
):
- Server actions for data mutations
- Business rules and validations
- Integration with external services
Data Layer (database/
):
- Database schema definitions
- Data models and relationships
- Migration management
2. Configuration Over Code
- Centralized config - Change behavior without touching components
- Type-safe configuration - TypeScript ensures correctness
- Environment-based - Different configs for dev/staging/production
3. Modular Architecture
- Independent modules - AI, credits, payment, mail, storage are self-contained
- Provider pattern - Easy to implement your own providers
- Feature folders - Related code stays together
Directory Reference
Here's a quick reference for finding specific functionality:
Frontend
- Pages →
src/app/
- Components →
src/components/
- Styles →
src/app/globals.css
,src/styles/
- Assets →
public/
Backend
- Database →
src/database/
- API Routes →
src/app/api/
- Server Actions →
src/lib/actions/
,src/[feature]/actions/
- Authentication →
src/lib/auth/
Business Logic
- AI →
src/ai/
- Credits →
src/credits/
- Payment →
src/payment/
- Email →
src/mail/
- Storage →
src/storage/
Configuration
- App Config →
src/config/
- Content →
src/content/
- Translations →
messages/
- Environment →
.env.local
Development
- Migrations →
drizzle/
- Docker →
Dockerfile
- Types →
src/types/
Common Patterns
Adding a New Feature
- Create page route in
src/app/
- Build components in
src/components/[feature]/
- Add server actions in
src/lib/actions/
orsrc/[feature]/actions/
- Update configuration in
src/config/
- Add translations in
messages/
Adding a New Payment Provider
- Create provider in
src/payment/providers/new-provider.ts
- Implement required interface
- Update
src/payment/actions/
- Add config in
src/config/index.ts
- Update webhook handler in
src/app/api/webhooks/
Adding a New AI Model
- Add model config in
src/ai/models/
- Update prompts in
src/ai/prompts.ts
- Create API route in
src/app/api/ai/
- Add UI components in
src/components/examples/ai/
Adding a New Language
- Create
messages/[locale].json
- Add locale to
src/config/index.ts
- Update
src/i18n/routing.ts
- Test with
http://localhost:3000/[locale]
Next Steps
Now that you understand the architecture:
- Explore the code - Open files and see how they connect
- Try making changes - Modify a component or config
- Read specific guides - Authentication, payments, credits, AI integration
- Build your feature - Apply these patterns to your use case
The architecture is designed to grow with your application while maintaining clarity and maintainability.