Menu

after

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

它可以在 Server Components(包括 generateMetadata)、Server ActionsRoute HandlersProxy 中使用。

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

app/layout.tsx
TypeScript
import { after } from 'next/server'
// 自定义日志函数
import { log } from '@/app/utils'
 
export default function Layout({ children }: { children: React.ReactNode }) {
  after(() => {
    // 在布局渲染并发送给用户后执行
    log()
  })
  return <>{children}</>
}

值得注意的是after 不是 Dynamic API,调用它不会导致路由变为动态的。如果在静态页面中使用它,回调函数将在构建时或页面重新验证时执行。

参考

参数

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

持续时间

after 将在你的路由的平台默认或配置的最大持续时间内运行。如果你的平台支持,你可以使用 maxDuration 路由段配置来配置超时限制。

值得注意的是

  • 即使响应未成功完成,after 也会执行。包括当抛出错误或调用 notFoundredirect 时。
  • 你可以使用 React cache 来去重在 after 内部调用的函数。
  • after 可以嵌套在其他 after 调用中,例如,你可以创建包装 after 调用的实用函数来添加额外的功能。

示例

使用请求 API

你可以在 Server ActionsRoute Handlersafter 中使用请求 API,例如 cookiesheaders。这对于在变更后记录活动非常有用。例如:

app/api/route.ts
TypeScript
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'
 
export async function POST(request: Request) {
  // 执行变更
  // ...
 
  // 记录用户活动用于分析
  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' },
  })
}

但是,你不能在 Server Componentsafter 中使用这些请求 API。这是因为 Next.js 需要知道树的哪一部分访问了请求 API 以支持 Cache Components,但 after 在 React 的渲染生命周期之后运行。

平台支持

部署选项支持
Node.js server
Docker container
Static export
Adapters特定于平台

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

参考:为 serverless 平台支持 after

在 serverless 上下文中使用 after 需要在响应发送后等待异步任务完成。在 Next.js 和 Vercel 中,这是通过一个名为 waitUntil(promise) 的原语实现的,它将 serverless 调用的生命周期延长到传递给 waitUntil 的所有 promise 都已结算。

如果你希望你的用户能够运行 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>()
 
// 定义并注入 next.js 将使用的访问器
const RequestContext: NextRequestContext = {
  get() {
    return RequestContextStorage.getStore()
  },
}
globalThis[Symbol.for('@next/request-context')] = RequestContext
 
const handler = (req, res) => {
  const contextValue = { waitUntil: YOUR_WAITUNTIL }
  // 提供值
  return RequestContextStorage.run(contextValue, () => nextJsHandler(req, res))
}

版本历史

版本描述
v15.1.0after 变为稳定版。
v15.0.0-rc引入 unstable_after