Next.js is an open-source framework based on React, designed to simplify the complexity of web development while providing powerful features for building modern, high-performance applications. It’s particularly well-suited for building applications with Server-Side Rendering (SSR), Static Site Generation (SSG), and Client-Side Rendering (CSR).
1. Introduction to Next.js
Next.js was developed by Vercel and first released in 2016. It’s a “full-stack” React framework with many built-in features like routing, data fetching, optimization, and more. Key features include:
- Zero Configuration: Start development without complex Webpack or Babel configurations.
- Hybrid Rendering: Support for SSR, SSG, and CSR, allowing flexible choice based on requirements.
- File System Routing: Automatically generates routes based on file and folder structure.
- API Routes: Allows creation of backend API endpoints within the same project.
- Automatic Optimization: Built-in image optimization, code splitting, and on-demand loading.
2. Core Features
2.1 File System Routing
- When you create files in the
pagesfolder, Next.js automatically maps them to routes. For example:pages/index.js->/pages/about.js->/aboutpages/blog/[id].js->/blog/1(dynamic route)
- Supports nested routes and dynamic routes:
- Dynamic routes use square brackets
[param], e.g.,[id].js. - Optional parameters use
[[...slug]]to capture optional path segments.
- Dynamic routes use square brackets
2.2 Rendering Modes
Next.js provides several rendering methods:
- Static Site Generation (SSG):
- Generates HTML at build time, uses
getStaticPropsto fetch data. - Suitable for pages with content that doesn’t change frequently (like blogs, documentation).
- Example:
export async function getStaticProps() { const data = await fetchData(); return { props: { data } }; }
- Generates HTML at build time, uses
- Server-Side Rendering (SSR):
- Generates HTML on each request, uses
getServerSideProps. - Suitable for scenarios where content updates frequently.
- Example:
export async function getServerSideProps(context) { const { params } = context; return { props: { id: params.id } }; }
- Generates HTML on each request, uses
- Client-Side Rendering (CSR):
- Uses React’s
useEffector other methods to fetch data on the client side.
- Uses React’s
- Incremental Static Regeneration (ISR):
- Combines the advantages of SSG, allowing periodic updates of static content at runtime.
- Add the
revalidateparameter ingetStaticProps:return { props: { data }, revalidate: 10 }; // Updates every 10 seconds
2.3 API Routes
- Create files in the
pages/apifolder to define backend interfaces. - Example:
// pages/api/hello.js export default function handler(req, res) { res.status(200).json({ message: "Hello, World!" }); } - Supports HTTP methods (like GET, POST), determined by
req.method.
2.4 Image Optimization
- The
<Image>component automatically optimizes images, supporting lazy loading, format conversion, and size adjustment. - Example:
import Image from "next/image"; export default function Home() { return <Image src="/example.jpg" alt="Example" width={500} height={300} />; }
2.5 CSS and Styling
- Supports CSS Modules (
*.module.css), Sass, Tailwind CSS, etc. - Global styles are placed in the
stylesfolder or imported through_app.js. - Example (CSS Module):
/* styles/Home.module.css */ .container { padding: 20px; }import styles from "../styles/Home.module.css"; export default function Home() { return <div className={styles.container}>Hello</div>; }
3. Core Concepts
3.1 _app.js and _document.js
_app.js: Customizes the application entry point, can wrap global components or add global state.import "../styles/global.css"; export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; }_document.js: Customizes HTML document structure, typically used to add content to the<head>tag.import { Html, Head, Main, NextScript } from "next/document"; export default function Document() { return ( <Html> <Head /> <body> <Main /> <NextScript /> </body> </Html> ); }
3.2 Data Fetching
getStaticProps: Fetches data at build time, used for SSG.getServerSideProps: Fetches data at request time, used for SSR.getStaticPaths: Used withgetStaticPropsto specify paths for dynamic routes.export async function getStaticPaths() { return { paths: [{ params: { id: "1" } }, { params: { id: "2" } }], fallback: "blocking", // Or true/false }; }
3.3 Link Component and Navigation
- Use the
<Link>component for client-side navigation, avoiding page refreshes. - Example:
import Link from "next/link"; export default function Home() { return <Link href="/about">Go to About</Link>; }
4. Advanced Features
4.1 TypeScript Support
- Next.js natively supports TypeScript, just change files to
.tsor.tsx. - Create
tsconfig.json:npx create-next-app@latest --ts
4.2 Middleware
- Defined in
middleware.js, used to handle requests (such as redirects, authentication). - Example:
import { NextResponse } from "next/server"; export function middleware(req) { if (req.nextUrl.pathname === "/admin") { return NextResponse.redirect(new URL("/", req.url)); } }
4.3 Internationalization (i18n)
- Configure multi-language support in
next.config.js:module.exports = { i18n: { locales: ["en", "zh"], defaultLocale: "en", }, };
4.4 Deployment
- Next.js applications can be easily deployed to Vercel, or exported as static files:
npm run build npm run export
5. Best Practices
- Code Splitting: Utilize Next.js’s automatic code splitting to reduce first screen loading time.
- SEO Optimization: Use the
<Head>component to add meta tags.import Head from "next/head"; export default function Home() { return ( <> <Head> <title>My Page</title> <meta name="description" content="Description" /> </Head> <h1>Hello</h1> </> ); } - Performance Optimization: Use SSG or ISR when possible to reduce server load.
6. Version Evolution
- Next.js 13 (2022): Introduced App Router (
appdirectory), replacingpagesrouting, supporting more flexible layouts and server components. - Next.js 14 (2023): Optimized server components and build speed, further improved developer experience.
Summary
Next.js is a powerful and easy-to-use framework suitable for development ranging from small projects to enterprise applications. Its core advantages lie in the flexibility of rendering modes, simplicity of routing, and built-in optimization features.
Comments