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

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

# @xid-kit/nextjs

## Middleware

`xidMiddleware()` 在 Edge Runtime 上运行，无需网络即可验证会话 JWT，并将认证状态注入下游请求头，供服务端组件和路由处理器使用。

```ts
import { xidMiddleware } from '@xid-kit/nextjs'

export default xidMiddleware({
  jwtKey: process.env.XID_JWKS_PUBLIC_KEY!,
  issuer: 'https://xid.dev',
})

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

## App Router 服务端辅助工具

```ts
import { auth, currentUser } from '@xid-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 '@xid-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

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

## 重新导出

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

Source: https://xid.dev/zh-hans/sdks/nextjs/index.mdx
