Next.js
Next.js
A React-based full-stack framework. Supports SSR, SSG, and API Routes.
Next.js
A React-based full-stack framework. Supports SSR, SSG, and API Routes.
Next.js is a React-based full-stack framework developed by Vercel. It supports various rendering strategies such as server-side rendering (SSR), static site generation (SSG), and incremental static regeneration (ISR), greatly improving SEO optimization and initial loading performance. With file-based routing, you can structure pages without complex configuration.
The App Router, introduced in Next.js 13, natively supports React Server Components. Server components run only on the server by default, which reduces the client bundle size and allows direct access to databases and the file system. Client components are used with the 'use client' directive only when client-side interaction is needed.
Through API Routes (or Route Handlers), you can implement backend APIs within the same project, which makes full-stack development possible. Database connections, authentication, external API calls, and more can be handled without a separate backend server. It also supports the Edge Runtime, so you can run APIs and middleware at CDN edges around the world.
Next.js has built-in production optimization features such as image optimization (next/image), font optimization (next/font), and script optimization (next/script). Dev server startup speed and HMR (Hot Module Replacement) performance have been greatly improved through Turbopack (a Rust-based bundler).
// === App Router ꡬ쑰 (Next.js 13+) ===
// app/layout.tsx - λ£¨νΈ λ μ΄μμ (νμ)
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: { default: 'My App', template: '%s | My App' },
description: 'Next.js μ ν리μΌμ΄μ
',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ko">
<body className={inter.className}>
<header>{/* κ³΅ν΅ ν€λ */}</header>
{children}
<footer>{/* κ³΅ν΅ νΈν° */}</footer>
</body>
</html>
);
}
// app/page.tsx - μλ² μ»΄ν¬λνΈ (κΈ°λ³Έ)
import { ProductList } from './components/ProductList';
// μ μ λ©νλ°μ΄ν°
export const metadata = {
title: 'ν',
description: 'λ©μΈ νμ΄μ§μ
λλ€.',
};
// μλ²μμ μ§μ λ°μ΄ν° νμΉ (async μ»΄ν¬λνΈ)
async function getProducts() {
const res = await fetch('https://api.example.com/products', {
next: { revalidate: 3600 } // ISR: 1μκ°λ§λ€ μ¬μμ±
});
if (!res.ok) throw new Error('Failed to fetch');
return res.json();
}
export default async function HomePage() {
const products = await getProducts();
return (
<main>
<h1>μ ν λͺ©λ‘</h1>
<ProductList products={products} />
</main>
);
}
// app/components/ProductList.tsx - ν΄λΌμ΄μΈνΈ μ»΄ν¬λνΈ
'use client'; // ν΄λΌμ΄μΈνΈ μ»΄ν¬λνΈ μ§μμ΄
import { useState } from 'react';
import { Product } from '@/types';
export function ProductList({ products }: { products: Product[] }) {
const [filter, setFilter] = useState('');
const filtered = products.filter(p =>
p.name.toLowerCase().includes(filter.toLowerCase())
);
return (
<div>
<input
type="text"
placeholder="κ²μ..."
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
<ul>
{filtered.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
// app/products/[id]/page.tsx - λμ λΌμ°νΈ
import { notFound } from 'next/navigation';
// λμ λ©νλ°μ΄ν°
export async function generateMetadata({ params }: { params: { id: string } }) {
const product = await getProduct(params.id);
return { title: product?.name || 'Not Found' };
}
// μ μ μμ±ν κ²½λ‘ λ―Έλ¦¬ μμ±
export async function generateStaticParams() {
const products = await getProducts();
return products.map((product) => ({ id: product.id }));
}
export default async function ProductPage({ params }: { params: { id: string } }) {
const product = await getProduct(params.id);
if (!product) notFound();
return <div>{product.name}</div>;
}
// app/api/products/route.ts - Route Handler (API)
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const category = searchParams.get('category');
const products = await db.products.findMany({
where: category ? { category } : undefined
});
return NextResponse.json(products);
}
export async function POST(request: NextRequest) {
const body = await request.json();
const product = await db.products.create({
data: body
});
return NextResponse.json(product, { status: 201 });
}
// middleware.ts - μ μ λ―Έλ€μ¨μ΄
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// μΈμ¦ 체ν¬
const token = request.cookies.get('auth-token');
if (request.nextUrl.pathname.startsWith('/dashboard') && !token) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*']
};
"We need to choose a framework for a new project. Should we use Next.js or plain React?"
"If SEO or initial loading speed is important, Next.js is a good choice. Server components reduce the bundle size, and you can implement the backend together with API Routes. For an SPA that doesn't need SEO, like an admin page, plain React is fine too."
"Should we use the App Router or the Pages Router?"
"For a new project, I'd recommend the App Router. You can use the latest features like Server Components, nested layouts, and streaming. There's no need to rush to migrate existing projects; you can use both routers together and transition gradually."
"Can you explain the differences between SSR, SSG, and ISR in Next.js?"
"SSR generates HTML on the server for every request, and SSG generates HTML in advance at build time. ISR is SSG plus revalidation, which regenerates the page in the background at the time interval you set even after the build. You can easily configure it with fetch's revalidate option."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Server/client component distinction: In the App Router, components are server components by default. To use React hooks such as useState and useEffect, you must add 'use client' at the top of the file. Using client hooks in a server component causes an error.
Data fetching location: In server components, you can fetch data directly with async/await, but in client components you must use useEffect or a library such as SWR/React Query. Even if you use a sensitive API key in a server component, it is not exposed to the client.
Caching behavior: Next.js's fetch caches results by default. If you need real-time data, set cache: 'no-store', and if you need periodic refresh, use the revalidate option. If you don't understand the caching behavior, stale data may be displayed.