# ๐Ÿš€ Enterprise Next.js Boilerplate (Antigravity Edition) [![Next.js](https://img.shields.io/badge/Next.js%2016-000000?style=for-the-badge&logo=next.js&logoColor=white)](https://nextjs.org/) [![React](https://img.shields.io/badge/React%2019-61DAFB?style=for-the-badge&logo=react&logoColor=black)](https://react.dev/) [![Chakra UI](https://img.shields.io/badge/Chakra%20UI%20v3-319795?style=for-the-badge&logo=chakraui&logoColor=white)](https://chakra-ui.com/) [![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?style=for-the-badge&logo=typescript&logoColor=white)](https://www.typescriptlang.org/) [![next-intl](https://img.shields.io/badge/next--intl-0070F3?style=for-the-badge&logo=next.js&logoColor=white)](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.