English: Next.js is a React framework for building full-stack web applications. It extends React by providing automated optimization features like rendering strategies (SSR, SSG, ISR), routing, and simplified data fetching.
中文:Next.js 是一个用于构建全栈 Web 应用程序的 React 框架。它通过提供渲染策略(SSR、SSG、ISR)、路由和简化数据获取等自动优化功能扩展了 React。
English (Optimized):
fetch with caching and revalidation.中文:
fetch。While React.js is a library for building UIs, Next.js is a framework built on top of React, providing additional features such as SSR, SSG, and routing out of the box.
React 是一个用于构建 UI 的库;而 Next.js 是一个提供开箱即用基础设施(路由、数据获取、渲染)的框架。
Next.js offers Better SEO (Server Rendering), Zero-config, faster performance via automatic code splitting, and built-in full-stack capabilities.
更好的 SEO(服务端渲染)、零配置、通过自动代码拆分实现更快的性能,以及内置的全栈能力。
SSR in Next.js allows pages to be rendered on the server at request time, ensuring that the page's content is available to search engines and improving the initial load time.
SSR(服务端渲染):每次请求时在服务端渲染 HTML。适用于动态数据。
SSG generates HTML at build time for fast loading and improved SEO. It’s ideal for pages that don’t change often, such as blogs or marketing pages.
SSG(静态生成):构建时生成 HTML。性能最快。
API routes allow you to build backend functionality directly in your Next.js app. These are serverless functions that handle HTTP requests like GET, POST, PUT, etc.
ISR (Incremental Static Regeneration)
ISR enables static content to be updated after the site has been built, allowing you to regenerate pages in the background while serving static content to users.
ISR(增量静态再生):允许你在构建后通过 revalidate 更新静态页面,无需重新发布整个项目。
Dynamic routes in Next.js are handled using brackets ([]). For example, pages/[id].js will create dynamic routes based on the id parameter.
Next.js automatically splits code by page. This means only the necessary code for each page is loaded, improving performance and reducing bundle size.
The App Router in Next.js is a routing system introduced to simplify the routing mechanism, offering enhanced flexibility and control compared to the Pages Router.
App Router:v13 引入,使用 /app 目录并基于 React Server Components 构建。支持布局(Layouts)、嵌套路由和流式传输(Streaming)。
Layouts in the App Router allow you to structure reusable components across multiple pages, making it easier to manage UI consistency and shared components.
布局 (Layouts):layout.js 文件允许在路由间共享 UI,同时保留状态并避免重复渲染。
The app directory is used with the new App Router and supports features like layouts, loading states, and more advanced routing capabilities. The pages directory is used in the traditional Pages Router.
服务端组件 (默认):在服务端渲染。减少了客户端 JS,且能直接访问后端资源。
客户端组件:需添加 "use client" 指令。用于交互性功能(点击事件、状态、副作用)和浏览器 API。
Next.js supports SSR and SSG, which generates pre-rendered HTML content, making it more SEO-friendly compared to traditional client-side rendering (CSR).
Environment variables are handled via .env files (e.g., .env.local) and can be accessed in both the client and server-side code using process.env.
Dynamic API routes are created by using the same bracket notation ([param]) in the pages/api directory.
Middleware allows you to run code before a request is completed, enabling features like authentication, logging, or redirecting users.
中文: 中间件在请求完成之前运行。常用于身份验证、重定向和路径重写。
React Server Components allow parts of the UI to be rendered on the server, reducing the client-side JavaScript bundle size.
React Server Components allow rendering on the server, improving performance by sending only necessary JavaScript to the client.
To use React Server Components in Next.js, create a .server.js file in the appropriate directory, allowing the component to be rendered server-side.
next/link is a React component for client-side navigation, providing prefetching and reducing page reloads, unlike a standard <a> tag.
next/image automatically optimizes images for better performance, including resizing, lazy loading, and WebP support.
Rewrites allow you to map an incoming request path to a different destination without changing the URL in the browser.
next.config.js is a configuration file in Next.js that allows you to customize the build process, routing, environment variables, and more.
Next.js optimizes images by automatically resizing, compressing, and serving them in the most appropriate format for the client.
Hybrid rendering in Next.js allows you to use SSR, SSG, or ISR on a per-page basis, providing flexibility in how content is rendered.
Hybrid rendering offers the ability to combine different rendering strategies to maximize performance, SEO, and flexibility.
State management in Next.js can be done using React's useState and useContext, or with libraries like Redux or Zustand.
Routing in Next.js is based on the file system. The files in the app directory automatically become routes.
Nested routing is handled by creating subdirectories inside the app directory. For example, app/blog/[id].js supports dynamic routes.
The public folder is used for static assets like images, fonts, or other files that can be accessed directly via URL.
To create a custom 500 error page, create a pages/_error.js file and customize the error handling for both 404 and 500 errors.
File-based routing automatically maps files in the app directory to routes based on their file names and structure.
You can style components using traditional CSS, CSS-in-JS libraries like styled-components, or CSS modules.
Next.js has built-in support for TypeScript. You can create a tsconfig.json file, and it will automatically detect and work with TypeScript files.
Simply add a tsconfig.json file to your project root. Next.js will automatically configure TypeScript for you, and you can start using .ts and .tsx files.
English:
next/image, next/font, and next/script. loading.js. 中文: 1. 使用服务端组件减少客户端 JS。 2. 使用 next/image、next/font 和 next/script 优化资源。 3. 通过 loading.js 实现流式传输 (Streaming)。 4. 对大型客户端库使用动态导入。
ISR allows you to update static content after the site is built using revalidate in getStaticProps.
Redirects are configured in next.config.js using the redirects() function.
44、What is the difference between getStaticProps and getServerSideProps?
过时了,不用管。
Store variables in .env.local, and access them with process.env.MY_VAR. Prefix with NEXT_PUBLIC_ to use them in the client.
Use headers() in next.config.js to add custom HTTP headers.
Image component in Next.js?It’s a built-in component that optimizes images with lazy loading, resizing, and format conversion.
Using next/link, prefetching is enabled by default on visible links. You can also manually enable it with prefetch={true}.
useRouter and Link?useRouter: Hook to access routing methods.Link: Component for client-side navigation.Add a middleware.ts file in the root or a route directory to intercept requests and modify behavior.
中文: 在根目录创建一个 middleware.ts 文件。它使用 matcher 配置来过滤需要运行中间件的路由。
English: Middleware running on the Edge Runtime, closer to users for low-latency tasks like auth, geo-redirects, and A/B testing.
中文: 运行在 Edge Runtime 上的中间件,地理位置更接近用户,用于处理身份验证、地理重定向和 A/B 测试等低延迟任务。
English: Use Middleware to check session tokens before requests reach the page, or check auth status directly in Server Components.
中文: 使用中间件在请求到达页面前检查 Session Token,或者直接在服务端组件中检查授权状态。
Use libraries like express-rate-limit or custom logic inside API routes to track and limit requests.
revalidate property?English: It specifies the background regeneration interval in seconds. In App Router, use fetch(url, { next: { revalidate: 60 } }).
中文: 它指定了后台重新生成的间隔秒数。在 App Router 中通过 fetch 的 revalidate 参数实现。
English: Vercel is the optimized platform, but it can be deployed on any server supporting Node.js or via Docker.
中文: Vercel 是最推荐的平台,但也可以在任何支持 Node.js 的服务器或通过 Docker 部署。
Install Tailwind, add it to postcss.config.js, and import it in your main CSS file.
next dev, next build, and next start?next dev: Starts the dev servernext build: Builds the app for productionnext start: Starts the production server中文: dev 用于开发热更新;build 创建生产环境包;start 运行已构建的生产服务器。
English: App Router, Server Components, Server Actions, Turbopack, and React 19 support in v15.
中文: App Router、服务端组件、Server Actions、Turbopack 编译器,以及 v15 对 React 19 的支持。
ISR delivers static pages but allows them to be updated in the background, improving freshness and speed.
English: Use try-catch and return NextResponse.json() with appropriate status codes (400, 500).
中文: 使用 try-catch 并返回带有对应状态码(400, 500)的 NextResponse.json()。
English: Use the third-party-libraries or Vercel Analytics.
中文: 使用第三方库或 Vercel Analytics。在 App Router 中直接在 layout 注入脚本。
In App Router, use the root layout.
在 App 路由下使用根布局(Root Layout)。
In App Router, this is handled in layout.js.
在 App 路由下直接在根布局修改 HTML 结构。
Special files like loading.tsx used to show UI during lazy data fetching or navigation.
中文: loading.js 文件,利用 React Suspense 在数据获取期间显示即时加载状态。
English: A temporary UI shown during ISR when the static page hasn't been generated yet.
中文: ISR 期间,在静态页面尚未生成时显示的临时 UI。
They allow you to load components on demand using next/dynamic.
Define locales and defaultLocale in next.config.js, and Next.js will handle route-based translations.
English: Allows rendering multiple pages simultaneously in the same layout using slots (e.g., @sidebar).
中文: 允许在同一布局中使用插槽(如 @sidebar)同时渲染多个页面。
English: Intercepting a route to show content in the current context (e.g., a modal) while keeping the background.
中文: 拦截路由以便在当前上下文中显示内容(如弹窗),同时保留背景页面。
English: Yes, but it requires careful setup for Server Components; lightweight tools like Zustand are often preferred.
中文: 可以,但对于服务端组件需要复杂配置,通常更推荐 Zustand 等轻量工具。
English: Use the Metadata API (export const metadata) in layout.js or page.js.
中文: 使用 Metadata API(在布局或页面文件中导出 metadata 常量)。
English: Use native fetch with async/await directly inside Server Components.
中文: 直接在服务端组件中使用原生的 async/await fetch。
English: Create a not-found.js file in the app directory for custom 404 UI.
中文: 在 app 目录下创建 not-found.js 来自定义 404 界面。
next export?已过时。不用管。
I don't know, I didn't use it before.
English: Using better-auth for full-stack auth or middleware for session verification.
中文: 使用 better-auth 提供全栈身份验证,或通过中间件验证 Session。
English: Not natively, but you can build PWAs or use it as a backend API for React Native.
中文: 不能直接构建原生应用,但可以做 PWA,或作为 React Native 的后端 API。
Rendering HTML in advance either at build time (SSG) or request time (SSR).
中文: 在发送到客户端之前,在服务端预先生成 HTML(通过 SSG 或 SSR)。
English: Use a dynamic sitemap.ts file in the app directory to generate it programmatically.
中文: 在 app 目录中使用动态的 sitemap.ts 文件来编程生成站点地图。
English: Use a dynamic robots.ts file in the app directory.
中文: 在 app 目录中使用动态的 robots.ts 文件。
nglish: Use next/font/google for automatic self-hosting and zero layout shift.
中文: 使用 next/font/google 实现字体自动托管和零累计布局偏移。
Lazy loading in Next.js loads components/images only when they enter the viewport.
Use Jest and React Testing Library for unit/integration tests; Playwright or Cypress for E2E.
English: Global state libraries (Zustand, Redux) or URL search parameters for simple state sharing.
中文: 使用全局状态库(Zustand, Redux)或通过 URL 查询参数实现简单状态共享。
English: Yes, by connecting in Server Components or API route handlers.
中文: 可以,在服务端组件或 API 路由处理程序中进行连接。86. How to create breadcrumbs in Next.js?
Use useRouter to track path and build a breadcrumb component dynamically.
English: Use the usePathname hook to parse the URL segments into a navigation list.
中文: 使用 usePathname Hook 解析 URL 路径片段并构建导航列表。
English: Use semantic HTML, ARIA labels, and next/image alt text; test with Lighthouse.
中文: 使用语义化 HTML、ARIA 标签和图片 alt 属性;使用 Lighthouse 进行审计。
English: Use loading.js for route-level spinners or React state for component-level ones.
中文: 路由级别使用 loading.js;组件级别使用 React 状态控制。
English: Use next-themes library to manage CSS variables and local storage.
中文: 使用 next-themes 库来管理 CSS 变量和本地存储。
It’s when content moves during load.we can prevent it by using next/image and next/font.
中文: 内容在加载期间移动;通过使用 next/image 和 next/font 并设置固定尺寸来预防。
English: The process where client-side JavaScript attaches to the static HTML to make it interactive.
中文: 客户端 JavaScript 绑定到静态 HTML 上使其变得可交互的过程。
English: CSR renders in the browser; SSR renders the initial HTML on the server.
中文: CSR 在浏览器渲染;SSR 在服务端生成初始 HTML。
English: Components that render on the server only, reducing the JS bundle sent to the client.
中文: 仅在服务端渲染的组件,减少了发送到客户端的 JS 体积。
English: Yes, using the cookies() function from next/headers in Server Components.
中文: 可以,在服务端组件中使用 next/headers 提供的 cookies() 函数。
English: Use Server Actions ("use server") to handle form data directly on the server.
中文: 使用 Server Actions 直接在服务端处理表单数据。
English: Set headers in next.config.js or directly within Route Handlers.
中文: 在 next.config.js 中设置响应头,或直接在 Route Handlers 中设置。
Use folders like components, app, lib, styles, public, and hooks for better organization.
English: Use next/font/local for self-hosted font files to ensure performance.
中文: 使用 next/font/local 托管本地字体文件以确保性能。
English: Create layout.js files in different folder segments to wrap child components.
中文: 在不同的文件夹层级创建 layout.js 文件来包裹子组件。
English: Check user roles in Middleware or within the root layout.js.
中文: 在中间件或根布局 layout.js 中检查用户角色。
English: Higher server costs for SSR; increased complexity with Server/Client component separation.
中文: SSR 导致的服务器成本较高;服务端/客户端组件分离带来的复杂度增加。
better-authtanstack querytailwindcss