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,同时保留状态并避免重复渲染。
不用管。
服务端组件 (默认):在服务端渲染。减少了客户端 JS,且能直接访问后端资源。
客户端组件:需添加 "use client" 指令。用于交互性功能(点击事件、状态、副作用)和浏览器 API。
Traditional Client-Side Rendering is bad for SEO because the server sends a blank HTML file. The search crawler has to wait for a massive JavaScript bundle to download and execute before it can read any content. If the bot times out, it indexes an empty page.
Next.js fixes this by shifting the rendering to the server using SSR or SSG. It delivers a fully populated HTML file to the browser immediately. When a search engine crawls the site, it can read all the text, links, and headings instantly without needing JavaScript.
On top of that, Next.js has built-in tools to easily inject dynamic meta tags directly from the server, and its faster initial load speeds up Core Web Vitals, which directly boosts Google rankings.
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 in Next.js is like a security guard at the entrance of your app. (Next.js 的中间件就像应用入口处的一个保安。)
Every request passes through it before the page renders. (在页面渲染之前,每一个请求都会经过它。)
It runs on the Edge, very close to the user. So it is extremely fast. (它运行在边缘网络,离用户非常近。所以它极其快速。)
I usually use it for two simple things: (我通常用它做两件简单的事:)
First, Authentication. It checks if the user is logged in. If not, it redirects them to the login page immediately. (第一是鉴权。它检查用户是否登录。如果没有,立刻把他们重定向到登录页。)
Second, Internationalization. It detects the user's language and opens the right language version. (第二是国际化。它检测用户的语言,并打开正确的语言版本。)
In short, it intercepts requests to handle security and routing early. (简而言之,它拦截请求,提前处理安全和路由逻辑。)
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.
Optimize performance in Next.js app, I focus on three main areas: Images, Code Splitting, and Caching. (优化 Next.js 的性能主要集中在三个领域:图片、代码分割和缓存。)
First, Image Optimization. I always use the built-in <Image /> component.
(第一,图片优化。我总是使用内置的 <Image /> 组件。)
It automatically resizes images and converts them to modern formats like WebP. This reduces page weight significantly. (它会自动调整图片大小并转换为 WebP 等现代格式。这显著减轻了页面体积。)
Second, Code Splitting. Next.js does this automatically by page. But for heavy third-party libraries, I use next/dynamic to lazy-load them only when needed.
(第二,代码分割。Next.js 会按页面自动处理。但对于大型第三方库,我用 next/dynamic 做到只有在需要时才懒加载。)
Third, Choosing the right rendering strategy. For static content, I use SSG or ISR to serve pre-rendered HTML instantly via CDN. I avoid doing expensive database fetches inside SSR if the data doesn't change often. (第三,选择正确的渲染策略。对于静态内容,我用 SSG 或 ISR 通过 CDN 瞬间送达。如果数据不经常变,我避免在 SSR 内部做高昂的数据库查询。)
Finally, I use Font Optimization and Script Optimization to prevent blocking the main thread. (最后,我使用字体优化和脚本优化来防止阻塞主线程。)
In short, my goal is to keep the initial JavaScript bundle small and the DOM paint fast. (简而言之,我的目标是保持初始 JS 体积小、DOM 渲染快。)
ISR stands for Incremental Static Regeneration. It is a mix of Static sites and Dynamic sites. (ISR 代表增量静态再生。它是静态网站和动态网站的结合体。)
With traditional static generation, you must rebuild the entire website to update one page. This is too slow for large sites. (在传统的静态生成中,你必须重新构建整个网站来更新某一个页面。对于大型网站来说这太慢了。)
ISR fixes this. It allows you to update a single static page in the background, without rebuilding the whole site. (ISR 解决了这个问题。它允许你在后台更新单个静态页面,而不需要重新构建整个网站。)
To use it, you just add a revalidate time in your fetch request, like revalidate: 60.
(要使用它,你只需要在 fetch 请求中添加一个重新验证时间,比如 revalidate: 60。)
This means Next.js will keep the page static, but check for new data every 60 seconds. (这意味着 Next.js 会保持该页面为静态,但每隔 60 秒会检查一次新数据。)
I usually use ISR for pages like Product Detail pages or Blogs, where data changes sometimes, but not every second. (我通常将 ISR 用于商品详情页或博客,这些页面的数据偶尔会变,但不是每秒钟都在变。)
There are three main ways to handle redirects in Next.js, depending on when you want them to happen. (在 Next.js 中,有三种主要处理重定向的方法,取决于你希望它们在什么时候发生。)
First, inside the Configuration File (next.config.js).
(第一,在 配置文件 里。)
I use this for permanent or temporary URL changes that apply to the whole site. It is set up before the app runs, so it is great for SEO and legacy paths. (我用它来做整个网站的永久或临时 URL 更改。它在应用运行前配置好,所以对 SEO 和旧路径非常友好。)
Second, inside Middleware. (第二,在 中间件 里。)
I use this for dynamic redirects, like checking if a user is authenticated. If the user has no token, the middleware blocks them and redirects them to the login page immediately before the page even renders. (我用它来做动态重定向,比如检查用户是否通过身份验证。如果用户没有 Token,中间件会在页面渲染前立刻拦截并重定向到登录页。)
Third, inside Server Components or Client Components. (第三,在 服务端组件或客户端组件 内部。)
For Server Components, I use the redirect() function from next/navigation. It triggers instantly during the server render.
(对于服务端组件,我使用来自 next/navigation 的 redirect() 函数。它在服务端渲染期间立刻触发。)
For Client Components, I use router.push() inside an event handler, like after a user successfully clicks a submit button.
(对于客户端组件,我在事件处理函数(比如用户成功点击提交按钮后)内部使用 router.push()。)
In short: config for permanent paths, middleware for authentication, and hooks for user actions. (简而言之:配置用于永久路径,中间件用于身份验证,而钩子函数用于用户操作。)
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.
"Next.js handles prefetching automatically to make page transitions feel instant.
There are two main ways this works:
First, the <Link> Component.
Whenever a <Link> component appears in the user's viewport, Next.js automatically prefetches that page in the background. It downloads the code for the new page before the user even clicks it.
Second, the router.prefetch() API.
If I need to prefetch a page programmatically, I can use the useRouter hook. For example, I can trigger router.prefetch('/dashboard') when a user hovers over a custom button.
A key performance tip: Prefetching only works in production mode. Also, if a page uses SSR (Server-Side Rendering), Next.js only prefetches the layout, not the dynamic database data, to save server resources.
In short, Next.js prefetches code automatically using <Link>, or manually using router.prefetch().
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 参数实现。
Vercel is the optimized platform, but it can be deployed on any server supporting Node.js or via 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 improves performance in two main ways: speed and server protection.
First, it is super fast for users.Because ISR pre-renders pages into static HTML, pages load instantly via CDN. Users don't have to wait for a database or server to render the page.
Second, it protects the server from heavy traffic.Instead of generating a page on every single click, the server only updates the page once in a while—for example, every 60 seconds.
So, if 10,000 users visit the site at the same time, the server only does the work once, not 10,000 times.
In short, ISR gives you the speed of a static site but keeps the data updated.
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 router时代了。
n the modern App Router, we don't use _document.js anymore. All HTML tags and metadata are handled directly inside the root layout.js file.
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.
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?已过时。不用管。
75.Can you use GraphQL in Next.js?
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 文件来编程生成站点地图。
80.How do you create a robots.txt?
Use a dynamic robots.ts file in the app directory.
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 查询参数实现简单状态共享。
85.Can you use MongoDB with Next.js?
English: Yes, by connecting in Server Components or API route handlers.
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