Skip to content

自托管

¥Self-Hosting

当你的 Next.js 应用 deploying 时,你可能需要根据你的基础架构配置如何处理不同的功能。

¥When deploying your Next.js app, you may want to configure how different features are handled based on your infrastructure.

🎥 观看:了解有关自托管 Next.js → YouTube(45 分钟) 的更多信息。

¥🎥 Watch: Learn more about self-hosting Next.js → YouTube (45 minutes).

图片优化

¥Image Optimization

使用 next start 部署时,图片优化next/image 以零配置自托管。如果你希望使用单独的服务来优化图片,你可以 配置图片加载器

¥Image Optimization through next/image works self-hosted with zero configuration when deploying using next start. If you would prefer to have a separate service to optimize images, you can configure an image loader.

通过在 next.config.js 中定义自定义图片加载器,图片优化可以与 静态导出 一起使用。请注意,图片是在运行时优化的,而不是在构建期间优化的。

¥Image Optimization can be used with a static export by defining a custom image loader in next.config.js. Note that images are optimized at runtime, not during the build.

需要了解:

¥Good to know:

  • 在基于 glibc 的 Linux 系统上,图片优化可能需要 附加配置 来防止过度使用内存。

    ¥On glibc-based Linux systems, Image Optimization may require additional configuration to prevent excessive memory usage.

  • 了解有关 优化图片的缓存行为 以及如何配置 TTL 的更多信息。

    ¥Learn more about the caching behavior of optimized images and how to configure the TTL.

  • 如果你愿意,你也可以选择 禁用图片优化,同时仍然保留使用 next/image 的其他好处。例如,如果你自己单独优化图片。

    ¥You can also disable Image Optimization and still retain other benefits of using next/image if you prefer. For example, if you are optimizing images yourself separately.

中间件

¥Middleware

使用 next start 部署时,中间件 以零配置自托管工作。由于它需要访问传入请求,因此使用 静态导出 时不支持它。

¥Middleware works self-hosted with zero configuration when deploying using next start. Since it requires access to the incoming request, it is not supported when using a static export.

中间件使用 边缘运行时(所有可用 Node.js API 的子集)来帮助确保低延迟,因为它可能在应用中每个路由或资源的前面运行。如果你不想这样,可以使用 完整的 Node.js 运行时 运行中间件。

¥Middleware uses the Edge runtime, a subset of all available Node.js APIs to help ensure low latency, since it may run in front of every route or asset in your application. If you do not want this, you can use the full Node.js runtime to run Middleware.

如果你希望添加需要所有 Node.js API 的逻辑(或使用外部包),你也许可以将此逻辑移至 layout 作为 服务器组件。例如,检查 headersredirecting。你还可以对 redirectrewritenext.config.js 使用标头、cookie 或查询参数。如果这不起作用,你还可以使用 定制服务器

¥If you are looking to add logic (or use an external package) that requires all Node.js APIs, you might be able to move this logic to a layout as a Server Component. For example, checking headers and redirecting. You can also use headers, cookies, or query parameters to redirect or rewrite through next.config.js. If that does not work, you can also use a custom server.

环境变量

¥Environment Variables

Next.js 可以支持构建时和运行时环境变量。

¥Next.js can support both build time and runtime environment variables.

默认情况下,环境变量仅在服务器上可用。要将环境变量公开给浏览器,必须以 NEXT_PUBLIC_ 为前缀。但是,这些公共环境变量将在 next build 期间内联到 JavaScript 包中。

¥By default, environment variables are only available on the server. To expose an environment variable to the browser, it must be prefixed with NEXT_PUBLIC_. However, these public environment variables will be inlined into the JavaScript bundle during next build.

要读取运行时环境变量,我们建议使用 getServerSideProps逐步采用应用路由

¥To read runtime environment variables, we recommend using getServerSideProps or incrementally adopting the App Router.

这允许你使用单个 Docker 映像,该映像可以通过具有不同值的多个环境进行提升。

¥This allows you to use a singular Docker image that can be promoted through multiple environments with different values.

需要了解:

¥Good to know:

缓存和 ISR

¥Caching and ISR

Next.js 可以缓存响应、生成的静态页面、构建输出以及其他静态资源(例如图片、字体和脚本)。

¥Next.js can cache responses, generated static pages, build outputs, and other static assets like images, fonts, and scripts.

缓存和重新验证页面(使用 增量静态再生)使用相同的共享缓存。默认情况下,此缓存存储到 Next.js 服务器上的文件系统(磁盘上)。当使用 Pages 和 App Router 进行自托管时,此功能会自动起作用。

¥Caching and revalidating pages (with Incremental Static Regeneration) use the same shared cache. By default, this cache is stored to the filesystem (on disk) on your Next.js server. This works automatically when self-hosting using both the Pages and App Router.

如果你想要将缓存的页面和数据持久保存到持久存储,或者在 Next.js 应用的多个容器或实例之间共享缓存,你可以配置 Next.js 缓存位置。

¥You can configure the Next.js cache location if you want to persist cached pages and data to durable storage, or share the cache across multiple containers or instances of your Next.js application.

自动缓存

¥Automatic Caching

  • Next.js 将 public, max-age=31536000, immutableCache-Control 标头设置为真正不可变的资源。它不能覆盖。这些不可变文件的文件名中包含 SHA 哈希值,因此可以无限期安全地缓存它们。例如,静态图片导入。你可以对图片进行 配置 TTL

    ¥Next.js sets the Cache-Control header of public, max-age=31536000, immutable to truly immutable assets. It cannot be overridden. These immutable files contain a SHA-hash in the file name, so they can be safely cached indefinitely. For example, Static Image Imports. You can configure the TTL for images.

  • 增量静态再生 (ISR) 设置 s-maxage: <revalidate in getStaticProps>, stale-while-revalidateCache-Control 标头。此重新验证时间在 getStaticProps 功能 中以秒为单位定义。如果设置 revalidate: false,则默认缓存期限为一年。

    ¥Incremental Static Regeneration (ISR) sets the Cache-Control header of s-maxage: <revalidate in getStaticProps>, stale-while-revalidate. This revalidation time is defined in your getStaticProps function in seconds. If you set revalidate: false, it will default to a one-year cache duration.

  • 动态渲染的页面将 Cache-Control 标头设置为 private, no-cache, no-store, max-age=0, must-revalidate,以防止缓存用户特定的数据。这适用于 App Router 和 Pages Router。这还包括 草稿模式

    ¥Dynamically rendered pages set a Cache-Control header of private, no-cache, no-store, max-age=0, must-revalidate to prevent user-specific data from being cached. This applies to both the App Router and Pages Router. This also includes Draft Mode.

静态资源

¥Static Assets

如果你想将静态资源托管在不同的域或 CDN 上,可以使用 next.config.js 中的 assetPrefix configuration。Next.js 在检索 JavaScript 或 CSS 文件时将使用此资源前缀。将你的资源分离到不同的域确实会带来在 DNS 和 TLS 解析上花费额外时间的缺点。

¥If you want to host static assets on a different domain or CDN, you can use the assetPrefix configuration in next.config.js. Next.js will use this asset prefix when retrieving JavaScript or CSS files. Separating your assets to a different domain does come with the downside of extra time spent on DNS and TLS resolution.

了解有关 assetPrefix 的更多信息

¥Learn more about assetPrefix.

配置缓存

¥Configuring Caching

默认情况下,生成的缓存资源将存储在内存(默认为 50mb)和磁盘上。如果你使用 Kubernetes 等容器编排平台托管 Next.js,则每个 Pod 都将拥有一份缓存副本。由于默认情况下 Pod 之间不共享缓存,为了防止显示过时数据,你可以配置 Next.js 缓存以提供缓存处理程序并禁用内存中缓存。

¥By default, generated cache assets will be stored in memory (defaults to 50mb) and on disk. If you are hosting Next.js using a container orchestration platform like Kubernetes, each pod will have a copy of the cache. To prevent stale data from being shown since the cache is not shared between pods by default, you can configure the Next.js cache to provide a cache handler and disable in-memory caching.

要在自托管时配置 ISR/数据缓存位置,你可以在 next.config.js 文件中配置自定义处理程序:

¥To configure the ISR/Data Cache location when self-hosting, you can configure a custom handler in your next.config.js file:

然后,在项目的根目录中创建 cache-handler.js,例如:

¥Then, create cache-handler.js in the root of your project, for example:

使用自定义缓存处理程序将允许你确保托管 Next.js 应用的所有 pod 之间的一致性。例如,你可以将缓存的值保存在任何地方,例如 Redis 或 AWS S3。

¥Using a custom cache handler will allow you to ensure consistency across all pods hosting your Next.js application. For instance, you can save the cached values anywhere, like Redis or AWS S3.

需要了解:

¥Good to know:

  • revalidatePath 是缓存标签之上的便利层。调用 revalidatePath 将调用 revalidateTag 函数,并为所提供的页面提供特殊的默认标记。

    ¥revalidatePath is a convenience layer on top of cache tags. Calling revalidatePath will call the revalidateTag function with a special default tag for the provided page.

构建缓存

¥Build Cache

Next.js 在 next build 期间生成一个 ID,以识别正在提供的应用版本。应使用相同的构建并启动多个容器。

¥Next.js generates an ID during next build to identify which version of your application is being served. The same build should be used and boot up multiple containers.

如果你要为环境的每个阶段进行重建,则需要生成一致的构建 ID 以在容器之间使用。在 next.config.js 中使用 generateBuildId 命令:

¥If you are rebuilding for each stage of your environment, you will need to generate a consistent build ID to use between containers. Use the generateBuildId command in next.config.js:

版本偏差

¥Version Skew

Next.js 将自动缓解大多数 版本偏差 实例的影响,并在检测到时自动重新加载应用以检索新资源。例如,如果 deploymentId 不匹配,页面之间的转换将执行硬导航而不是使用预取值。

¥Next.js will automatically mitigate most instances of version skew and automatically reload the application to retrieve new assets when detected. For example, if there is a mismatch in the deploymentId, transitions between pages will perform a hard navigation versus using a prefetched value.

重新加载应用时,如果应用状态未设计为在页面导航之间保留,则可能会丢失应用状态。例如,使用 URL 状态或本地存储将在页面刷新后保留状态。但是,像 useState 这样的组件状态会在此类导航中丢失。

¥When the application is reloaded, there may be a loss of application state if it's not designed to persist between page navigations. For example, using URL state or local storage would persist state after a page refresh. However, component state like useState would be lost in such navigations.

手动优雅关闭

¥Manual Graceful Shutdowns

在自托管时,你可能希望在服务器因 SIGTERMSIGINT 信号关闭时运行代码。

¥When self-hosting, you might want to run code when the server shuts down on SIGTERM or SIGINT signals.

你可以将环境变量 NEXT_MANUAL_SIG_HANDLE 设置为 true,然后在 _document.js 文件中为该信号注册一个处理程序。你需要直接在 package.json 脚本中注册环境变量,而不是在 .env 文件中。

¥You can set the env variable NEXT_MANUAL_SIG_HANDLE to true and then register a handler for that signal inside your _document.js file. You will need to register the environment variable directly in the package.json script, and not in the .env file.

需要了解:next dev 中不支持手动信号处理。

¥Good to know: Manual signal handling is not available in next dev.