N Next.js 中文
原文 ↗

after

after 函数的 API 参考。

更新于 2026-09-16Next.js 16.4.6

after 允许你调度在响应(或预渲染)完成后执行的工作。这对于不应阻塞响应的任务和其他副作用(例如日志记录和分析)很有用。

它可用于服务器组件(包括 generateMetadata)、服务器函数、路由处理器和 Proxy。

该函数接受一个回调,该回调将在响应(或预渲染)完成后执行:

TypeScript

app/layout.tsxtsx
import { after } from 'next/server'
// Custom logging function
import { log } from '@/app/utils'

export default function Layout({ children }: { children: React.ReactNode }) {
  after(() => {
    // Execute after the layout is rendered and sent to the user
    log()
  })
  return <>{children}</>
}

JavaScript

app/layout.jsxjsx
import { after } from 'next/server'
// Custom logging function
import { log } from '@/app/utils'

export default function Layout({ children }) {
  after(() => {
    // Execute after the layout is rendered and sent to the user
    log()
  })
  return <>{children}</>
}

须知:

after 不是请求时 API,调用它不会使路由变为动态路由。如果在静态页面中使用它,回调将在构建时执行,或在页面重新验证时执行。

参考

参数

  • 一个回调函数,将在响应(或预渲染)完成后执行。

时长

after 将按照平台默认的或为你路由配置的最长时长运行。如果你的平台支持,可以使用 maxDuration 路由段配置来配置超时限制。

须知

  • 即使响应未成功完成,after 也会被执行。这包括抛出错误时,或调用了 notFound 或 redirect 时。
  • 在服务器组件中,你可以使用 React cache 来对在 after 内部调用的函数进行去重。回调会复用渲染期间已计算的值。请参阅使用 React.cache 复用数据。
  • after 可以嵌套在其他 after 调用中,例如,你可以创建包装 after 调用的工具函数,以添加额外的功能。

示例

搭配请求 API

能否在 after 内部使用诸如 cookies 和 headers 之类的请求 API,取决于 after 的调用位置。

在路由处理器和服务器函数中

在路由处理器和服务器函数中使用时,你可以直接在 after 回调内部调用 cookies 和 headers。这对于在变更或 API 请求之后记录活动很有用。例如:

TypeScript

app/api/route.tsts
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'

export async function POST(request: Request) {
  // Perform mutation
  // ...

  // Log user activity for analytics
  after(async () => {
    const userAgent = (await headers()).get('user-agent') || 'unknown'
    const sessionCookie =
      (await cookies()).get('session-id')?.value || 'anonymous'

    logUserAction({ sessionCookie, userAgent })
  })

  return new Response(JSON.stringify({ status: 'success' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  })
}

JavaScript

app/api/route.jsjs
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'

export async function POST(request) {
  // Perform mutation
  // ...

  // Log user activity for analytics
  after(async () => {
    const userAgent = (await headers()).get('user-agent') || 'unknown'
    const sessionCookie =
      (await cookies()).get('session-id')?.value || 'anonymous'

    logUserAction({ sessionCookie, userAgent })
  })

  return new Response(JSON.stringify({ status: 'success' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  })
}

在服务器组件中(页面和布局)

服务器组件(包括页面、布局和 generateMetadata)不能在 after 内使用 cookies、headers 或其他请求时 API。这是因为 Next.js 需要知道组件树中哪一部分访问了请求数据,以支持部分预渲染和缓存组件,而 after 在 React 的渲染生命周期之后运行。

如果你需要在服务器组件的 after 回调内访问请求数据,请提前读取并传入这些值:

TypeScript

app/page.tsxtsx
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'

export default async function Page() {
  // Read request data before `after` — this is allowed
  // These calls will be read during the component's rendering lifecycle
  const userAgent = (await headers()).get('user-agent') || 'unknown'
  const sessionCookie =
    (await cookies()).get('session-id')?.value || 'anonymous'

  after(() => {
    // Use the values read above
    logUserAction({ sessionCookie, userAgent })
  })

  return <h1>My Page</h1>
}

JavaScript

app/page.jsxjsx
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'

export default async function Page() {
  // Read request data before `after` — this is allowed
  // These calls will be read during the component's rendering lifecycle
  const userAgent = (await headers()).get('user-agent') || 'unknown'
  const sessionCookie =
    (await cookies()).get('session-id')?.value || 'anonymous'

  after(() => {
    // Use the values read above
    logUserAction({ sessionCookie, userAgent })
  })

  return <h1>My Page</h1>
}

在服务器组件的 after 回调中调用 cookies() 或 headers() 会抛出运行时错误。

使用缓存组件时

使用缓存组件时,访问请求数据(如 cookies 或 headers)的组件必须包裹在 <Suspense> 中,以便页面的其余部分可以预渲染为静态外壳。

你可以将此模式与 after 结合使用:在动态组件中读取请求数据,并将其传入 after:

TypeScript

app/page.tsxtsx
import { Suspense } from 'react'
import { after } from 'next/server'
import { cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'

export default function Page() {
  return (
    <>
      <h1>Part of the static shell</h1>
      <Suspense fallback={<p>Loading...</p>}>
        <DynamicContent />
      </Suspense>
    </>
  )
}

async function DynamicContent() {
  const sessionCookie =
    (await cookies()).get('session-id')?.value || 'anonymous'

  // Schedule work after the response is sent
  after(() => {
    logUserAction({ sessionCookie })
  })

  return <p>Your session: {sessionCookie}</p>
}

JavaScript

app/page.jsxjsx
import { Suspense } from 'react'
import { after } from 'next/server'
import { cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'

export default function Page() {
  return (
    <>
      <h1>Part of the static shell</h1>
      <Suspense fallback={<p>Loading...</p>}>
        <DynamicContent />
      </Suspense>
    </>
  )
}

async function DynamicContent() {
  const sessionCookie =
    (await cookies()).get('session-id')?.value || 'anonymous'

  // Schedule work after the response is sent
  after(() => {
    logUserAction({ sessionCookie })
  })

  return <p>Your session: {sessionCookie}</p>
}

在此示例中,<h1> 和 <Suspense> 回退内容包含在静态外壳中。DynamicContent 在渲染期间读取 cookie,并通过闭包将其传入 after。由于 cookies() 是在 after 回调之外(组件的渲染期间)调用的,因此可以正常工作。

平台支持

部署选项 是否支持
Node.js 服务器 是
Docker 容器 是
静态导出 否
适配器 视平台而定

了解在自托管 Next.js 时如何配置 after。

参考:在无服务器平台上支持 after

在无服务器环境中使用 after 需要在响应发送后等待异步任务完成。在 Next.js 和 Vercel 中,这是通过一个名为 waitUntil(promise) 的原语实现的,它会延长无服务器调用的生命周期,直到传递给 waitUntil 的所有 promise 均已 settled。

如果你希望用户能够运行 after,你需要提供行为类似的 waitUntil 实现。

当调用 after 时,Next.js 会像这样访问 waitUntil:

const RequestContext = globalThis[Symbol.for('@next/request-context')]
const contextValue = RequestContext?.get()
const waitUntil = contextValue?.waitUntil

这意味着 globalThis[Symbol.for('@next/request-context')] 应包含如下对象:

type NextRequestContext = {
  get(): NextRequestContextValue | undefined
}

type NextRequestContextValue = {
  waitUntil?: (promise: Promise<any>) => void
}

以下是实现示例。

import { AsyncLocalStorage } from 'node:async_hooks'

const RequestContextStorage = new AsyncLocalStorage<NextRequestContextValue>()

// Define and inject the accessor that next.js will use
const RequestContext: NextRequestContext = {
  get() {
    return RequestContextStorage.getStore()
  },
}
globalThis[Symbol.for('@next/request-context')] = RequestContext

const handler = (req, res) => {
  const contextValue = { waitUntil: YOUR_WAITUNTIL }
  // Provide the value
  return RequestContextStorage.run(contextValue, () => nextJsHandler(req, res))
}

版本历史

版本 变更
v15.1.0 after 已稳定。
v15.0.0-rc 引入 unstable_after。