---
title: "@vonvon-kit/nextjs"
description: "Next.js middleware、App Router 和 Pages Router 服务端辅助工具，以及 React SDK 的重新导出。"
locale: "zh-Hans"
---

> Documentation Index
> Fetch the relevant documentation index at: https://vonvon.id/zh-hans/sdks/llms.txt
> Use this file to discover all available pages before exploring further.

# @vonvon-kit/nextjs

## Middleware

Registry 状态:UNPUBLISHED。此 SDK 只能从仓库源码 checkout 安装；不要使用外部 package registry。

`vonvonMiddleware()` 在 Edge Runtime 上验证 Bearer 或显式应用 JWT。对于同源 Core session，它通过 `/v1/sessions/token` exchange opaque cookie，验证返回的 JWT，并将认证状态注入下游服务端请求头。

```ts
import { vonvonMiddleware } from '@vonvon-kit/nextjs'

export default vonvonMiddleware({
  jwtKey: JSON.parse(process.env.VONVON_JWKS_PUBLIC_KEY!),
  issuer: 'https://vonvon.id',
  // This same-origin path must be routed to Vonvon Core.
  sessionTokenExchange: { endpoint: '/v1/sessions/token' },
})

export const config = {
  matcher: ['/dashboard(.*)', '/api/protected(.*)'],
}
```

## App Router 服务端辅助工具

```ts
import { auth, currentUser } from '@vonvon-kit/nextjs'

export default async function DashboardPage() {
  const { userId } = await auth()
  if (!userId) return null
  const user = await currentUser()
  return <p>Welcome {user?.email}</p>
}
```

## Pages Router

```ts
import { getAuth } from '@vonvon-kit/nextjs'

export const getServerSideProps = async (ctx) => {
  const { userId } = await getAuth(ctx.req)
  if (!userId) return { redirect: { destination: '/sign-in', permanent: false } }
  return { props: {} }
}
```

## 导出的 API

| 导出 | 类型 | 用途 |
| --- | --- | --- |
| `vonvonMiddleware` | function | Edge Runtime middleware：验证 JWT 并注入认证请求头 |
| `auth` | function | App Router：返回包含 userId、orgId、orgRole 的 AuthObject |
| `getAuth` | function | Pages Router：从 IncomingMessage 返回 AuthObject |
| `currentUser` | function | App Router：使用服务端认证上下文获取完整用户对象 |
| `vonvonClient` | function | 返回绑定到当前请求认证的服务端 VonvonApiClient |
| `VONVON_AUTH_HEADER` | 字符串常量 | middleware 和服务端组件之间传递认证状态的请求头名称 |
| `VonvonMiddlewareOptions` | type | vonvonMiddleware 的选项：jwtKey、issuer、jwtCookieName、sessionTokenExchange、protectedRoutes、publicRoutes |
| `VonvonServerClientOptions` | type | vonvonClient 的选项 |
| `AuthObject` | type | 已认证状态：userId、orgId、orgRole、sessionId |
| `UnauthenticatedAuthObject` | type | 字段为 null 的未认证状态 |
| `AuthResult` | type | AuthObject 和 UnauthenticatedAuthObject 的联合类型 |
| `PaginationParams` | type | Management API 列表调用的 cursor 和 limit 参数 |
| `PaginatedResponse<T>` | type | 分页响应封装 |

## 重新导出

- 通过 `export * from \"@vonvon-kit/react\"` 重新导出所有 [@vonvon-kit/react](/zh-hans/sdks/react) 客户端组件和 hooks。
- 来自 [@vonvon-kit/backend](/zh-hans/sdks/backend) 的重新导出：`verifyToken`、`verifyWebhook`、`authenticateRequest`、`JwksCache`、`toVerifyKeySet`、`AppError`、`BACKEND_ERROR_CODES` 及其所有关联类型。
- 服务端辅助工具永远不会将签名密钥暴露给客户端 bundle。

Source: https://vonvon.id/zh-hans/sdks/nextjs/index.mdx
