after
after 函数的 API 参考。
after 允许您安排要在响应(或预渲染)完成后执行的工作。这适用于不应阻塞响应的任务和其他副作用,例如日志记录和分析。
它可以在 Server Components(包括 generateMetadata)、Server Functions、Route Handlers 和 Proxy 中使用。
该函数接受一个回调,该回调将在响应(或预渲染)完成后执行:
import { after } from 'next/server'
// 自定义日志函数
import { log } from '@/app/utils'
export default function Layout({ children }: { children: React.ReactNode }) {
after(() => {
// 在布局渲染并发送给用户后执行
log()
})
return <>{children}</>
}import { after } from 'next/server'
// 自定义日志函数
import { log } from '@/app/utils'
export default function Layout({ children }) {
after(() => {
// 在布局渲染并发送给用户后执行
log()
})
return <>{children}</>
}小知识:
after不是 Request-time API,调用它不会使路由变为动态。如果它在静态页面中使用,回调将在构建时执行,或在页面重新验证时执行。
参考#
参数#
- 一个回调函数,将在响应(或预渲染)完成后执行。
持续时间#
after 将按照平台的默认或配置的最大持续时间运行。如果您的平台支持,可以使用 maxDuration 路由段配置来设置超时限制。
小知识#
after即使响应未成功完成也会执行,包括抛出错误或调用notFound或redirect的情况。- 在 Server Components 中,您可以使用 React 的
cache对after内部调用的函数进行去重。回调会复用渲染期间已计算的值。请参阅使用React.cache复用数据。 after可以嵌套在其他after调用中,例如,您可以创建包装after调用的实用函数来添加额外功能。
示例#
使用请求 API#
是否可以在 after 中使用 cookies 和 headers 等请求 API,取决于 after 的调用位置。
在 Route Handlers 和 Server Functions 中#
在 Route Handlers 和 Server Functions 中使用时,您可以直接在 after 回调中调用 cookies 和 headers。这适用于在变更操作或 API 请求后记录活动。例如:
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' },
})
}import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'
export async function POST(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 Components(页面和布局)中#
Server Components(包括页面、布局和 generateMetadata)不能在 after 内部使用 cookies、headers 或其他 Request-time APIs。这是因为 Next.js 需要知道组件树的哪一部分访问请求数据,以支持部分预渲染(Partial Prerendering)和 Cache Components,而 after 在 React 的渲染生命周期之后运行。
如果您需要在 Server Component 的 after 回调中使用请求数据,请事先读取并传入这些值:
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'
export default async function Page() {
// 在 `after` 之前读取请求数据 —— 这是允许的
// 这些调用将在组件的渲染生命周期内被读取
const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie =
(await cookies()).get('session-id')?.value || 'anonymous'
after(() => {
// 使用上面读取的值
logUserAction({ sessionCookie, userAgent })
})
return <h1>My Page</h1>
}import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'
export default async function Page() {
// 在 `after` 之前读取请求数据 —— 这是允许的
// 这些调用将在组件的渲染生命周期内被读取
const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie =
(await cookies()).get('session-id')?.value || 'anonymous'
after(() => {
// 使用上面读取的值
logUserAction({ sessionCookie, userAgent })
})
return <h1>My Page</h1>
}在 Server Component 的 after 回调中调用 cookies() 或 headers() 将抛出运行时错误。
使用 Cache Components#
使用 Cache Components 时,访问 cookies 或 headers 等请求数据的组件必须用 <Suspense> 包裹,以便页面的其余部分可以预渲染为静态 shell。
您可以通过在动态组件中读取请求数据并将其传入 after,将此模式与 after 结合使用:
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'
// 在响应发送后安排工作
after(() => {
logUserAction({ sessionCookie })
})
return <p>Your session: {sessionCookie}</p>
}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'
// 在响应发送后安排工作
after(() => {
logUserAction({ sessionCookie })
})
return <p>Your session: {sessionCookie}</p>
}在此示例中,<h1> 和 <Suspense> 的 fallback 都包含在静态 shell 中。DynamicContent 在渲染期间读取 cookie,并通过闭包将其传入 after。由于 cookies() 是在 after 回调之外调用的(在组件渲染期间),因此可以正常工作。
平台支持#
| 部署选项 | 支持情况 |
|---|---|
| Node.js 服务器 | 是 |
| Docker 容器 | 是 |
| 静态导出 | 否 |
| 适配器 | 视平台而定 |
了解在自托管 Next.js 时如何配置 after。
<details id="after-serverless"> <summary>参考:为无服务器平台支持 after</summary>
在无服务器环境中使用 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>()
// 定义并注入 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))
}</details>
版本历史#
| 版本 | 变更 |
|---|---|
v15.1.0 | after 变为稳定版。 |
v15.0.0-rc | 引入 unstable_after。 |