Next.js 13+ is a full-stack React framework built on the new App Router architecture, leveraging React Server Components for optimal performance, SEO, and developer experience. Here's how modern Next.js works:
1. File-Based Routing with the app
Directory: The new App Router uses the
app/
directory where folders define routes and special files like page.tsx
,
layout.tsx
, and loading.tsx
control the UI. Dynamic routes use brackets like
[id]/page.tsx
.
app/
layout.tsx // Root layout
page.tsx // Home page
about/
page.tsx // /about route
blog/
[slug]/
page.tsx // /blog/[slug] route
layout.tsx // Blog layout
2. React Server Components (RSC): By default, all components in the App Router are Server Components that render on the server. This means:
'use client'
directive for interactive components// Server Component (default)
export default async function BlogPost({ params }) {
const post = await db.post.findUnique({ where: { slug: params.slug } });
return <article>{post.content}</article>;
}
// Client Component
('use client');
export function InteractiveButton() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
3. Modern Data Fetching:
async/await
useEffect
or libraries like SWRloading.tsx
and Suspense4. Nested Layouts: Layouts are shared UI that persist across routes and don't re-render on navigation:
// app/layout.tsx - Root layout
export default function RootLayout({ children }) {
return (
<html>
<body>
<Header />
{children}
<Footer />
</body>
</html>
);
}
5. Route Handlers (API Routes): API routes in the App Router use standard Web APIs:
// app/api/posts/route.ts
export async function GET() {
const posts = await db.post.findMany();
return Response.json(posts);
}
export async function POST(request) {
const body = await request.json();
// Handle POST request
}
6. Middleware and Edge Runtime: Middleware runs before requests are processed, perfect for authentication, redirects, and A/B testing:
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(request) {
if (!request.cookies.get('auth')) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
7. Performance Optimisations:
Summary: Modern Next.js with the App Router fundamentally changes how we build React apps by making Server Components the default, providing better performance through streaming and caching, and offering a more intuitive developer experience with nested layouts and colocation of related files.
Let me know what you think