N Next.js 中文
原文 ↗

支持不可变静态资源

在适配器中支持不可变静态资源

更新于 2026-07-20Next.js 16.4.6

有关此功能的面向最终用户的信息,请参阅 config.supportsImmutableAssets。

启用 config.supportsImmutableAssets 后,Next.js 会在公共路径 /_next/static/immutable/* 下输出不可变的内容寻址静态资源。此前缀可用于在 CDN 层面区分不可变静态资源与非不可变静态资源。

在运行时,请求这些不可变静态资源时不带 ?dpl 查询参数,因此它们位于跨部署共享的命名空间中。你必须确保这些资源不可变,并且不会被更改(即使在新部署之后),也不会被删除(只要仍有使用它们的活跃部署)。Next.js 可能会使用截断后的较短内容哈希作为文件名,因此 outputs.staticFiles[].immutableHash 包含完整内容哈希,可用于验证没有发生哈希冲突。

如果出于任何原因(例如检测到哈希冲突后)需要轮换哈希,你可以使用 config.outputHashSalt 为内容哈希设置盐值。

请注意,你仍需继续支持非不可变静态资源(这些资源可能在部署之间发生变化,并且仍会使用 ?dpl 查询参数请求),例如用于 public 文件夹或较旧的 Next.js 版本。

适配器实现

你需要:

  1. 在 modifyConfig 中,将 config.supportsImmutableAssets 属性设置为 true(如果用户尚未将其设置为 false),以表明你支持部署不可变静态资源,并且
  2. 在 onBuildComplete 中,读取 outputs.staticFiles[].immutableHash 属性,以确定哪些静态资源是不可变的,并且必须在不带 ?dpl 查询参数的情况下请求。
my-adapter.jsjs
/** @type {import('next').NextAdapter} */
const adapter = {
  name: 'my-custom-adapter',

  async modifyConfig(config, { phase }) {
    if (phase === 'phase-production-build') {
      config.supportsImmutableAssets =
        // Default to true, but allow users to opt-out
        config.supportsImmutableAssets ?? true

      // Optionally, pass a salt for the content hashes
      // config.outputHashSalt = getSaltForCurrentProject()
    }
    return config
  },

  async onBuildComplete({ outputs }) {
    for (const output of outputs.staticFiles) {
      if (output.immutableHash != null) {
        // This has to be requestable at `output.pathname`
        // even without the `?dpl` query parameter.
        uploadOrVerifyImmutableStaticAsset(
          output.filePath,
          output.pathname,
          output.immutableHash
        )
      } else {
        // This is a non-immutable static asset and will be requested with
        // the `?dpl` query parameter, scoped to the deployment.
        uploadStaticAsset(output.filePath, output.pathname)
      }
    }

    // Process other outputs....
  },
}