Menu

after

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

它可以在服务器组件(包括generateMetadata)、服务器操作路由处理程序中间件中使用。

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

app/layout.tsx
TypeScript
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}</>
}

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

参考

参数

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

持续时间

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

值得注意的是

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

示例

与请求 API 一起使用

你可以在服务器操作路由处理程序after 中使用请求 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) {
  // 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' },
  })
}

然而,你不能在服务器组件after 中使用这些请求 API。这是因为 Next.js 需要知道树的哪一部分访问请求 API 以支持部分预渲染,但 after 在 React 的渲染生命周期之后运行。

平台支持

部署选项支持情况
Node.js 服务器
Docker 容器
静态导出
适配器平台特定

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

参考:支持无服务器平台的 after 在无服务器上下文中使用 after 需要在响应发送后等待异步任务完成。在 Next.js 和 Vercel 中,这是通过一个称为 waitUntil(promise) 的原语实现的,它延长了无服务器调用的生命周期,直到传递给 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>()
 
// 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.0after 变为稳定版。
v15.0.0-rc引入 unstable_after