跳到主要内容

生产清单

在将 Next.js 应用投入生产之前,你应该考虑实现一些优化和模式,以获得最佳的用户体验、性能和安全性。

¥Before taking your Next.js application to production, there are some optimizations and patterns you should consider implementing for the best user experience, performance, and security.

本页提供了你在 构建你的应用在投入生产之前部署后 时可以用作参考的最佳实践 - 以及你应该注意的 自动 Next.js 优化

¥This page provides best practices that you can use as a reference when building your application, before going to production, and after deployment - as well as the automatic Next.js optimizations you should be aware of.

自动优化

¥Automatic optimizations

这些 Next.js 优化默认启用,无需配置:

¥These Next.js optimizations are enabled by default and require no configuration:

  • 服务器组件:Next.js 默认使用服务器组件。服务器组件在服务器上运行,不需要 JavaScript 在客户端上渲染。因此,它们对客户端 JavaScript 包的大小没有影响。然后,你可以根据需要使用 客户端组件 进行交互。

    ¥**Server Components:** Next.js uses Server Components by default. Server Components run on the server, and don't require JavaScript to render on the client. As such, they have no impact on the size of your client-side JavaScript bundles. You can then use Client Components as needed for interactivity.

  • 代码分割:服务器组件支持按路由段自动进行代码分割。在适当的情况下,你还可以考虑 延迟加载 客户端组件和第三方库。

    ¥**Code-splitting:** Server Components enable automatic code-splitting by route segments. You may also consider lazy loading Client Components and third-party libraries, where appropriate.

  • 预请求:当指向新路由的链接进入用户的视口时,Next.js 会在后台预取该路由。这使得导航到新路由几乎是即时的。你可以在适当的情况下选择退出预取。

    ¥**Prefetching:** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate.

  • 静态渲染:Next.js 在构建时在服务器上静态渲染服务器和客户端组件,并缓存渲染结果以提高应用的性能。如果适用,你可以选择使用 动态渲染 来获取特定路由。

    ¥**Static Rendering:** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into Dynamic Rendering for specific routes, where appropriate.

  • 缓存:Next.js 缓存数据请求、服务器和客户端组件的渲染结果、静态资源等,以减少对服务器、数据库和后端服务的网络请求数量。在适当的情况下,你可以选择退出缓存。

    ¥**Caching:** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate.

这些默认值旨在提高应用的性能,并降低每个网络请求传输的成本和数据量。

¥These defaults aim to improve your application's performance, and reduce the cost and amount of data transferred on each network request.

开发期间

¥During development

在构建应用时,我们建议使用以下功能以确保最佳性能和用户体验:

¥While building your application, we recommend using the following features to ensure the best performance and user experience:

路由和渲染

¥Routing and rendering

很高兴知道:部分预渲染(实验性) 将允许部分路由动态化,而无需将整个路由选择为动态渲染。

¥Good to know: Partial Prerendering (experimental) will allow parts of a route to be dynamic without opting the whole route into dynamic rendering.

数据获取和缓存

¥Data fetching and caching

  • 服务器组件:利用使用服务器组件在服务器上获取数据的优势。

    ¥**Server Components:** Leverage the benefits of fetching data on the server using Server Components.

  • 路由处理程序:使用路由处理程序从客户端组件访问后端资源。但不要从服务器组件调用路由处理程序以避免额外的服务器请求。

    ¥**Route Handlers:** Use Route Handlers to access your backend resources from Client Components. But do not call Route Handlers from Server Components to avoid an additional server request.

  • 流式:使用 Loading UI 和 React Suspense 逐步将 UI 从服务器发送到客户端,并防止在获取数据时整个路由阻塞。

    ¥**Streaming:** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched.

  • 并行数据获取:在适当的情况下,通过并行获取数据来减少网络瀑布。另外,在适当的情况下考虑 预加载数据

    ¥**Parallel Data Fetching:** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider preloading data where appropriate.

  • 数据缓存:验证你的数据请求是否正在缓存,并在适当的情况下选择缓存。确保不使用 fetch 的请求是 cached

    ¥**Data Caching:** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use fetch are cached.

  • 静态图片:使用 public 目录自动缓存应用的静态资源,例如 图片。

    ¥**Static Images:** Use the public directory to automatically cache your application's static assets, e.g. images.

用户界面和可访问性

¥UI and accessibility

  • 表格和验证:使用服务器操作来处理表单提交、服务器端验证和处理错误。

    ¥**Forms and Validation:** Use Server Actions to handle form submissions, server-side validation, and handle errors.

  • 字体模块:使用字体模块优化字体,该模块自动将你的字体文件与其他静态资源一起托管,删除外部网络请求,并减少 布局转变

    ¥**Font Module:** Optimize fonts by using the Font Module, which automatically hosts your font files with other static assets, removes external network requests, and reduces layout shift.

  • <Image> 组件:使用图片组件优化图片,该组件会自动优化图片,防止布局变化,并以 WebP 或 AVIF 等现代格式提供图片。

    ¥**<Image> Component:** Optimize images by using the Image Component, which automatically optimizes images, prevents layout shift, and serves them in modern formats like WebP or AVIF.

  • <Script> 组件:使用脚本组件优化第三方脚本,该组件会自动延迟脚本并防止它们阻塞主线程。

    ¥**<Script> Component:** Optimize third-party scripts by using the Script Component, which automatically defers scripts and prevents them from blocking the main thread.

  • ESLint:使用内置的 eslint-plugin-jsx-a11y 插件尽早发现可访问性问题。

    ¥**ESLint:** Use the built-in eslint-plugin-jsx-a11y plugin to catch accessibility issues early.

安全

¥Security

  • 污染:通过污染数据对象和/或特定值来防止敏感数据暴露给客户端。

    ¥**Tainting:** Prevent sensitive data from being exposed to the client by tainting data objects and/or specific values.

  • 服务器操作:确保用户有权调用服务器操作。查看推荐的 安全实践

    ¥**Server Actions:** Ensure users are authorized to call Server Actions. Review the recommended security practices.

  • 环境变量:确保你的 .env.* 文件已添加到 .gitignore,并且只有公共变量的前缀为 NEXT_PUBLIC_

    ¥**Environment Variables:** Ensure your .env.* files are added to .gitignore and only public variables are prefixed with NEXT_PUBLIC_.

  • 内容安全政策:考虑添加内容安全策略来保护你的应用免受各种安全威胁,例如跨站点脚本、点击劫持和其他代码注入攻击。

    ¥**Content Security Policy:** Consider adding a Content Security Policy to protect your application against various security threats such as cross-site scripting, clickjacking, and other code injection attacks.

元数据和搜索引擎优化

¥Metadata and SEO

  • 元数据 API:使用元数据 API 通过添加页面标题、描述等来改进应用的搜索引擎优化 (SEO)。

    ¥**Metadata API:** Use the Metadata API to improve your application's Search Engine Optimization (SEO) by adding page titles, descriptions, and more.

  • 开放图 (OG) 图片:创建 OG 图片以准备你的应用以进行社交共享。

    ¥**Open Graph (OG) images:** Create OG images to prepare your application for social sharing.

  • 站点地图机器人:通过生成站点地图和机器人文件,帮助搜索引擎抓取你的页面并为其建立索引。

    ¥**Sitemaps and Robots:** Help Search Engines crawl and index your pages by generating sitemaps and robots files.

类型安全

¥Type safety

  • TypeScript 和 TS 插件:使用 TypeScript 和 TypeScript 插件可以获得更好的类型安全性,并帮助你尽早发现错误。

    ¥TypeScript and TS Plugin: Use TypeScript and the TypeScript plugin for better type-safety, and to help you catch errors early.

投入生产之前

¥Before going to production

在投入生产之前,你可以运行 next build 在本地构建应用并捕获任何构建错误,然后运行 next start 来测量应用在类似生产环境中的性能。

¥Before going to production, you can run next build to build your application locally and catch any build errors, then run next start to measure the performance of your application in a production-like environment.

核心网络生命力

¥Core Web Vitals

  • 灯塔:以隐身方式运行 Lighthouse,以便更好地了解用户将如何体验你的网站,并确定需要改进的字段。这是一个模拟测试,应该与查看现场数据(例如 Core Web Vitals)结合起来。

    ¥**Lighthouse:** Run lighthouse in incognito to gain a better understanding of how your users will experience your site, and to identify areas for improvement. This is a simulated test and should be paired with looking at field data (such as Core Web Vitals).

  • useReportWebVitals:使用此钩子将 核心网络生命力 数据发送到分析工具。

    ¥**useReportWebVitals hook:** Use this hook to send Core Web Vitals data to analytics tools.

分析打包

¥Analyzing bundles

使用 @next/bundle-analyzer 插件 分析 JavaScript 包的大小并识别可能影响应用性能的大型模块和依赖。

¥Use the @next/bundle-analyzer plugin to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance.

此外,以下工具可以帮助你了解向应用添加新依赖的影响:

¥Additionally, the following tools can help you understand the impact of adding new dependencies to your application:

部署后

¥After deployment

根据你部署应用的位置,你可能可以访问其他工具和集成来帮助你监控和提高应用的性能。

¥Depending on where you deploy your application, you might have access to additional tools and integrations to help you monitor and improve your application's performance.

对于 Vercel 部署,我们建议如下:

¥For Vercel deployments, we recommend the following:

  • 分析:内置分析仪表板可帮助你了解应用的流量,包括唯一访问者数量、页面视图等。

    ¥**Analytics:** A built-in analytics dashboard to help you understand your application's traffic, including the number of unique visitors, page views, and more.

  • 速度洞察:基于访问者数据的真实性能洞察,提供有关你的网站在现场表现的实用视图。

    ¥**Speed Insights:** Real-world performance insights based on visitor data, offering a practical view of how your website is performing in the field.

  • 日志:运行时和活动日志可帮助你调试问题并监控生产中的应用。或者,请参阅 集成页面 以获取第三方工具和服务的列表。

    ¥**Logging:** Runtime and Activity logs to help you debug issues and monitor your application in production. Alternatively, see the integrations page for a list of third-party tools and services.

很高兴知道:

¥Good to know:

要全面了解 Vercel 上生产部署的最佳实践,包括提高网站性能的详细策略,请参阅 Vercel 生产清单

¥To get a comprehensive understanding of the best practices for production deployments on Vercel, including detailed strategies for improving website performance, refer to the Vercel Production Checklist.

遵循这些建议将帮助你为用户构建更快、更可靠、更安全的应用。

¥Following these recommendations will help you build a faster, more reliable, and secure application for your users.