Loading Blog Article...
Loading Blog Article...
Loading Blog Article...
A well-structured folder layout pays significant dividends for your development workflow. Here's a clean, scalable architecture for Next.js 13+ App Router projects that will keep your codebase maintainable as it grows.
project-root/
├─ app/ # App Router entry (Next.js 13+)
│ ├─ layout.tsx # Global layout (nav, fonts, theme)
│ ├─ page.tsx # Home page ("/")
│ ├─ api/ # Route Handlers (serverless APIs)
│ │ └─ v1/
│ │ └─ auth/
│ │ └─ route.ts # e.g. POST /api/v1/auth
│ ├─ dashboard/
│ │ ├─ layout.tsx # Dashboard-specific layout
│ │ ├─ page.tsx # "/dashboard"
│ │ └─ reports/
│ │ └─ page.tsx # "/dashboard/reports"
│ └─ error.tsx # Global error boundary
│
├─ components/ # Reusable UI components
│ ├─ Header/ Header.tsx
│ ├─ Footer/ Footer.tsx
│ └─ Button/ Button.tsx
│
├─ hooks/ # Custom React hooks
│ ├─ useAuth.ts
│ └─ useFetch.ts
│
├─ services/ # API/service layer (no UI here)
│ ├─ user/ userService.ts
│ └─ product/ productService.ts
│
├─ styles/ # Styling
│ ├─ globals.css # Imported in app/layout.tsx
│ ├─ variables.css # CSS vars / themes
│ └─ components/
│ ├─ Button.module.css
│ └─ Header.module.css
│
├─ types/ # Shared TypeScript types
│ └─ exampleDataType.ts
│
├─ public/ # Static assets (images, fonts, favicon)
│
├─ tests/ # Tests (unit/integration/e2e)
│ ├─ unit/
│ ├─ integration/
│ └─ e2e/
│
├─ .env.local # Local env vars (gitignored)
├─ next.config.js
├─ tsconfig.json
└─ package.jsonPro tip: Prefer colocation when it makes sense
// app/api/v1/auth/route.ts
import { NextResponse } from 'next/server';
export async function POST(req: Request) {
const body = await req.json();
// auth logic here…
return NextResponse.json({ ok: true });
}Server vs Client Components
'use client';
import { useEffect, useState } from 'react';
export function useFetch<T>(url: string) {
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<unknown>(null);
useEffect(() => {
let alive = true;
fetch(url)
.then(r => r.json())
.then(d => alive && setData(d))
.catch(e => alive && setError(e));
return () => { alive = false; };
}, [url]);
return { data, error };
}// services/user/userService.ts
export async function getUserProfile(token: string) {
const res = await fetch(`${process.env.NEXT_PUBLIC_API}/v1/user`, {
headers: { Authorization: `Bearer ${token}` },
next: { revalidate: 60 }, // ISR-style revalidation
});
if (!res.ok) throw new Error('Failed to load profile');
return res.json() as Promise<User>;
}Naming convention: Use *.test.ts(x) and consider keeping tests near the code they verify if your team prefers colocation.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["components/*"],
"@services/*": ["services/*"],
"@hooks/*": ["hooks/*"]
}
}
}