# ๐ Enterprise Next.js Boilerplate (Antigravity Edition)
[](https://nextjs.org/)
[](https://react.dev/)
[](https://chakra-ui.com/)
[](https://www.typescriptlang.org/)
[](https://next-intl-docs.vercel.app/)
> **FOR AI AGENTS & DEVELOPERS:** This documentation is structured to provide deep context, architectural decisions, and operational details to ensure seamless handover to any AI coding assistant (like Antigravity) or human developer.
---
## ๐ง Project Context & Architecture (Read Me First)
This is an **opinionated, production-ready** frontend boilerplate built with Next.js 16 App Router. It is designed to work seamlessly with the companion **typescript-boilerplate-be** NestJS backend.
### ๐๏ธ Core Philosophy
- **Type Safety First:** Strict TypeScript configuration. DTOs and typed API responses connect frontend to backend.
- **App Router Native:** Built entirely on Next.js App Router with Server Components and React Server Actions support.
- **i18n Native:** Localization is baked into routing, API calls, and UI components via `next-intl`.
- **Theme-First Design:** Chakra UI v3 with custom theme system for consistent, accessible UI.
- **Auth by Default:** NextAuth.js integration with JWT token management and automatic session handling.
### ๐ Architectural Decision Records (ADR)
_To understand WHY things are the way they are:_
1. **Locale-Based Routing:**
- **Mechanism:** All routes are prefixed with locale (e.g., `/tr/dashboard`, `/en/login`).
- **Implementation:** `next-intl` plugin with `[locale]` dynamic segment in `app/` directory.
- **Config:** `localePrefix: 'always'` ensures consistent URL structure.
2. **API Client with Auto-Auth & Locale:**
- **Location:** `src/lib/api/create-api-client.ts`
- **Feature:** Automatically injects JWT `Authorization` header from NextAuth session.
- **Feature:** Automatically sets `Accept-Language` header based on current locale (cookie or URL path).
- **Auto-Logout:** 401 responses trigger automatic signOut and redirect.
3. **Backend Proxy (CORS Solution):**
- **Problem:** Local development CORS issues when frontend (port 3001) calls backend (port 3000).
- **Solution:** Next.js `rewrites` in `next.config.ts` proxies `/api/backend/*` โ `http://localhost:3000/api/*`.
- **Usage:** API clients use `/api/backend/...` paths in development.
4. **Provider Composition:**
- **Location:** `src/components/ui/provider.tsx`
- **Stack:** `SessionProvider` (NextAuth) โ `ChakraProvider` (UI) โ `ColorModeProvider` (Dark/Light) โ `Toaster` (Notifications)
- **Why:** Single import in layout provides all necessary contexts.
---
## ๐ Quick Start for AI & Humans
### 1. Prerequisites
- **Node.js:** v20.19+ (LTS)
- **Package Manager:** `npm` (Lockfile: `package-lock.json`)
- **Backend:** Companion NestJS backend running on port 3000 (see `typescript-boilerplate-be`)
### 2. Environment Setup
```bash
cp .env.example .env.local
# Edit .env.local with your configuration
```
**Required Environment Variables:**
| Variable | Description | Example |
| --------------------------- | --------------------------------------------------------------- | --------------------------- |
| `NEXTAUTH_URL` | NextAuth callback URL | `http://localhost:3001` |
| `NEXTAUTH_SECRET` | Authentication secret (generate with `openssl rand -base64 32`) | `abc123...` |
| `NEXT_PUBLIC_API_URL` | Backend API base URL | `http://localhost:3001/api` |
| `NEXT_PUBLIC_AUTH_REQUIRED` | Require login for all pages | `true` or `false` |
### 3. Installation & Running
```bash
# Install dependencies
npm ci
# Development Mode (HTTPS enabled, port 3001)
npm run dev
# Production Build
npm run build
npm run start
```
> **Note:** Dev server runs on port 3001 with experimental HTTPS for secure cookie handling.
---
## ๐ Internationalization (i18n) Guide
Deep integration with `next-intl` provides locale-aware routing and translations.
### Configuration
- **Supported Locales:** `['en', 'tr']`
- **Default Locale:** `tr`
- **Locale Detection:** Cookie (`NEXT_LOCALE`) โ URL path โ Default
### File Structure
```
messages/
โโโ en.json # English translations
โโโ tr.json # Turkish translations
src/i18n/
โโโ routing.ts # Locale routing configuration
โโโ navigation.ts # Typed navigation helpers (Link, useRouter)
โโโ request.ts # Server-side i18n setup
```
### Usage in Components
```tsx
// Client Component
"use client";
import { useTranslations } from "next-intl";
export function MyComponent() {
const t = useTranslations("common");
return
{t("welcome")}
;
}
// Navigation with Locale
import { Link } from "@/i18n/navigation";
Dashboard; // Auto-prefixes with current locale
```
### Adding a New Locale
1. Add locale code to `src/i18n/routing.ts`:
```ts
export const locales = ["en", "tr", "de"]; // Add 'de'
```
2. Create `messages/de.json` with translations.
3. Update `getLocale()` in `create-api-client.ts` if needed.
---
## ๐ Authentication System
Built on NextAuth.js with JWT strategy for seamless backend integration.
### How It Works
1. **Login:** User submits credentials โ `/api/auth/[...nextauth]` โ Backend validates โ JWT returned.
2. **Session:** JWT stored in encrypted cookie, accessible via `useSession()` hook.
3. **API Calls:** `createApiClient()` automatically adds `Authorization: Bearer {token}` header.
4. **Auto-Refresh:** Token refreshed before expiry (managed by NextAuth).
### Protected Routes
```tsx
// Use middleware.ts or check session in layout
import { getServerSession } from "next-auth";
export default async function ProtectedLayout({ children }) {
const session = await getServerSession();
if (!session) redirect("/login");
return <>{children}>;
}
```
### Auth Mode Toggle
Set `NEXT_PUBLIC_AUTH_REQUIRED=true` for mandatory authentication across all pages.
---
## ๐จ UI System (Chakra UI v3)
### Theme Configuration
- **Location:** `src/theme/theme.ts`
- **Font:** Bricolage Grotesque (Google Fonts, variable font)
- **Color Mode:** Light/Dark with system preference detection
### Component Organization
```
src/components/
โโโ ui/ # Chakra UI wrapper components
โ โโโ provider.tsx # Root provider (Session + Chakra + Theme)
โ โโโ color-mode.tsx # Dark/Light mode toggle
โ โโโ feedback/ # Toaster, alerts, etc.
โ โโโ ...
โโโ layout/ # Page layout components (Header, Sidebar, Footer)
โโโ auth/ # Authentication forms and guards
โโโ site/ # Site-specific feature components
```
### Toast Notifications
```tsx
import { toaster } from "@/components/ui/feedback/toaster";
// Success toast
toaster.success({
title: "Saved!",
description: "Changes saved successfully.",
});
// Error toast
toaster.error({ title: "Error", description: "Something went wrong." });
```
---
## ๐ก API Integration
### Creating API Clients
```tsx
// src/lib/api/auth/login/queries.ts
import { createApiClient } from "../create-api-client";
const api = createApiClient("/api/backend/auth");
export const loginUser = async (data: LoginDto) => {
const response = await api.post("/login", data);
return response.data;
};
```
### React Query Integration
```tsx
import { useQuery, useMutation } from "@tanstack/react-query";
// Query hook
export const useUsers = () =>
useQuery({
queryKey: ["users"],
queryFn: () => apiClient.get("/users"),
});
// Mutation hook
export const useCreateUser = () =>
useMutation({
mutationFn: (data: CreateUserDto) => apiClient.post("/users", data),
});
```
---
## ๐ System Map (Directory Structure)
```
src/
โโโ app/ # Next.js App Router
โ โโโ [locale]/ # Locale-prefixed routes
โ โ โโโ (auth)/ # Auth pages (login, register)
โ โ โโโ (site)/ # Main site pages
โ โ โโโ (error)/ # Error pages
โ โ โโโ layout.tsx # Root layout with providers
โ โ โโโ page.tsx # Home page
โ โโโ api/ # Next.js API routes
โ โโโ auth/ # NextAuth endpoints
โโโ components/ # React components
โ โโโ ui/ # Chakra UI wrappers & base components
โ โโโ layout/ # Layout components (Header, Sidebar)
โ โโโ auth/ # Auth-related components
โ โโโ site/ # Feature-specific components
โโโ config/ # App configuration
โโโ hooks/ # Custom React hooks
โโโ i18n/ # Internationalization setup
โโโ lib/ # Utilities & services
โ โโโ api/ # API clients (organized by module)
โ โ โโโ auth/ # Auth API (login, register)
โ โ โโโ admin/ # Admin API (roles, users)
โ โ โโโ create-api-client.ts # Axios factory with interceptors
โ โโโ services/ # Business logic services
โ โโโ utils/ # Helper functions
โโโ theme/ # Chakra UI theme configuration
โโโ types/ # TypeScript type definitions
โโโ proxy.ts # API proxy utilities
messages/ # Translation JSON files
public/ # Static assets
```
---
## ๐งช Testing & Development
### Available Scripts
```bash
npm run dev # Start dev server (HTTPS, port 3001)
npm run build # Production build
npm run start # Start production server
npm run lint # Run ESLint
```
### Development Tools
- **React Compiler:** Enabled for automatic optimization.
- **Top Loader:** Visual loading indicator for route transitions.
- **ESLint + Prettier:** Consistent code formatting.
---
## ๐ ๏ธ Troubleshooting (Known Issues)
**1. HTTPS Certificate Warnings in Development**
- **Context:** Dev server uses `--experimental-https` for secure cookies.
- **Fix:** Accept the self-signed certificate warning in your browser.
**2. Backend Connection Refused**
- **Fix:** Ensure NestJS backend is running on port 3000.
- **Check:** Run `curl http://localhost:3000/api/health` to verify.
**3. Session Not Persisting**
- **Fix:** Ensure `NEXTAUTH_SECRET` is set and consistent between restarts.
- **Fix:** Check that cookies are not blocked by browser settings.
**4. Locale Not Detected**
- **Context:** Default falls back to `tr` if cookie/URL detection fails.
- **Fix:** Clear `NEXT_LOCALE` cookie and refresh.
---
## ๐ Related Projects
- **Backend:** [typescript-boilerplate-be](../typescript-boilerplate-be) - NestJS backend with Prisma, JWT auth, and i18n.
---
## ๐ License
This project is proprietary and confidential.