# @frontegg/nextjs 中文文档

规范地址：https://npmcn.com/package/%40frontegg/nextjs/

版本：9\.2\.14
npm 元数据更新时间：2026-09-29T12:20:34.017Z
中文译文更新时间：2026-11-15T14:49:27.995Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40frontegg/nextjs
原文对照：https://npmcn.com/package/%40frontegg/nextjs/?lang=original
项目主页：https://github.com/frontegg/frontegg-nextjs#readme
源码仓库：https://github.com/frontegg/frontegg-nextjs

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：704 kB，267 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：5 个
- peer 依赖：react ^16\.9\.0 \|\| ^17\.0\.0 \|\| ^18\.0\.0 \|\| ^19\.0\.0，react-dom ^16\.9\.0 \|\| ^17\.0\.0 \|\| ^18\.0\.0 \|\| ^19\.0\.0
- 首次发布：2021-08-11T12:07:31.786Z
- 最新版本发布：2026-09-29T12:20:33.736Z
- 近 30 天下载量：43252（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：714（近 12 个月 12 个）

## 中文简介

![alt text](https://raw.githubusercontent.com/frontegg/frontegg-nextjs/master/logo.png)

## 安装

```sh
npm install @frontegg/nextjs
```

也可以使用：`pnpm add @frontegg/nextjs`、`yarn add @frontegg/nextjs`、`bun add @frontegg/nextjs`

## README

![alt text](https://raw.githubusercontent.com/frontegg/frontegg-nextjs/master/logo.png)

Frontegg是一个网络平台,SaaS公司可以在此建立其完全管理,可扩展和品牌意识的平台-SaaS功能 并把它们整合到他们的SaaS门户中,多达5行代码.

## 目录

-   [安装](https://npmcn.com/package/%40frontegg/nextjs/#readme-installation)
    -   [创建下个 JS 项目](https://npmcn.com/package/%40frontegg/nextjs/#readme-create-new-nextjs-project)
    -   [添加到现有项目](https://npmcn.com/package/%40frontegg/nextjs/#readme-add-to-existing-project)
    -   [使用自定义域的 Vercel 平台](https://npmcn.com/package/%40frontegg/nextjs/#readme-using-vercel-platform-with-custom-domain)
-   [开始](https://npmcn.com/package/%40frontegg/nextjs/#readme-getting-started)
    -   [创建 Frontegg 工作空间](https://npmcn.com/package/%40frontegg/nextjs/#readme-create-frontegg-workspace)
    -   [设置环境](https://npmcn.com/package/%40frontegg/nextjs/#readme-setup-environment)
-   [文档](https://npmcn.com/package/%40frontegg/nextjs/#readme-documentation)
    -   [API 参考](https://npmcn.com/package/%40frontegg/nextjs/#readme-api-reference)
    -   [Frontegg 提供方选项](https://npmcn.com/package/%40frontegg/nextjs/#readme-frontegg-provider-options)
    -   [获取会议](https://npmcn.com/package/%40frontegg/nextjs/#readme-getsession)
    -   [与届会](https://npmcn.com/package/%40frontegg/nextjs/#readme-withssrsession)
    -   [Next.js 中间软件的使用](https://npmcn.com/package/%40frontegg/nextjs/#readme-nextjs-middlewares-usage)
    -   为了更多 [访问](https://docs.frontegg.com/docs/self-service-introduction)
-   [警卫](https://npmcn.com/package/%40frontegg/nextjs/#readme-security)

## 安装

### 将 Frontegg 添加到 Next.JS 项目

要将 Frontegg 添加到您的 Next.JS 项目中, 请遵循以下步骤 :

使用软件包管理器安装 Frontegg Next.JS 库.

```bash
  npm install --save @frontegg/nextjs
```

或者说

```bash
  yarn add --save @frontegg/nextjs
```

**如果您使用 App 目录架构, 您可以跳过以下 Pages 架构步骤并参考 [AppDir 引导](https://npmcn.com/package/%40frontegg/nextjs/#readme-nextjs-appdir-architecture) 换句话说.**

1.  环绕默认导出方式 `withFronteggApp` 内 `./pages/_app.tsx`数字 :
    
    ```tsx
    // ./pages/_app.tsx
    
    import { withFronteggApp } from "@frontegg/nextjs/pages";
    
    function CustomApp({ Component, pageProps }: AppProps) {
      return <Component {...pageProps} />;
    }
    
     export default withFronteggApp(CustomApp, {
       // when change to false, you have also to provide FRONTEGG_HOSTED_LOGIN='false' in .env.local
       hostedLoginBox: true
     });
    ```
    
2.  在下方创建前置中间软件的文件 `./pages/api/frontegg/[...frontegg-middleware].ts`数字 :
    
    ```tsx
    // ./pages/api/frontegg/[...frontegg-middleware].ts
    
    export { fronteggMiddleware as default } from '@frontegg/nextjs/middleware';
    ```
    
3.  在下面为前置路由器创建占位符页面 `./pages/[...frontegg-router].tsx`数字 :
    
    ```tsx
    // ./pages/[...frontegg-router].tsx
    
    export {
      FronteggRouter as default,
      FronteggRouterProps as getServerSideProps,
    } from '@frontegg/nextjs/pages';
    ```
    

### 使用自定义域的 Vercel 平台

1.  访问 `https://vercel.com/[ACCOUNT_ID]/[PROJECT_ID]/settings/environment-variables`
2.  添加 `FRONTEGG_APP_URL` 每个Vercel环境的环境变量 ![vercel-settings-pages](https://github.com/frontegg/frontegg-nextjs/blob/master/assets/vercel-environment.png)

## 开始

### 创建 Frontegg 工作空间

导航到 [Frontegg 门户设置](https://portal.frontegg.com/development/settings)如果您没有申请 注册后遵循整合步骤.

下一步, 在“ 设置” 页的“ 域” 标签下配置您的应用程序中的“ 全部来源 ” :

-   http://localhost:3:00/用于发展环境
-   [https://my-company-domain.com (中文(中国大陆) )](https://my-company-domain.com/) //用于生产环境

复制客户端ID, Frontegg Domain 从“ 设置” 页面复制, 您将在下一步需要这些值 .

### 设置环境

要设置您的 Next.js 应用程序以与 Frontegg 通信, 您必须创建一个名为 Frontegg 的新文件 `.env.local` 下级 您的根工程目录, 此文件将被用于存储将使用的环境变量, 配置 选项:

```dotenv
# The AppUrl is used to tell Frontegg your application hostname
FRONTEGG_APP_URL='http://localhost:3000'

# The Frontegg domain is your unique URL to connect to the Frontegg gateway
FRONTEGG_BASE_URL='https://{YOUR_SUB_DOMAIN}.frontegg.com'

# Your Frontegg application's Client ID
# - For Dev environment [visit](https://portal.frontegg.com/development/settings/general)
# - For Prod environment [visit](https://portal.frontegg.com/production/settings/general)
FRONTEGG_CLIENT_ID='{YOUR_APPLICATION_CLIENT_ID}'

# Your Frontegg application's Client Secret
# - For Dev environment [visit](https://portal.frontegg.com/development/settings/general)
# - For Prod environment [visit](https://portal.frontegg.com/production/settings/general)
FRONTEGG_CLIENT_SECRET='{YOUR_APPLICATION_CLIENT_SECRET}'

# The stateless session encryption password used to encrypt the JWT before sending it to the client side.
# For quick password generation, use the following command:
#    node -e "console.log(crypto.randomBytes(32).toString('hex'))"
FRONTEGG_ENCRYPTION_PASSWORD='{SESSION_ENCRYPTION_PASSWORD}'

# The stateless cookie name for storing the encrypted JWT
# value as session cookies for supporting getServerSideProps and ServerComponents
FRONTEGG_COOKIE_NAME='FRONTEGG_COOKIE_NAME'

# Specifies the domain for storing the encrypted JWT as session cookies, 
# enabling support for `getServerSideProps` and `ServerComponents`.  
# If not provided, the domain will be the same as the `APP_URL` environment variable.
FRONTEGG_COOKIE_DOMAIN='FRONTEGG_COOKIE_DOMAIN'

# The JWT public key generated by Frontegg to verify JWT before creating a session.
# Retrieve it by visiting: https://[YOUR_FRONTEGG_DOMAIN]/.well-known/jwks.json.
# By default, this key will be fetched from the Frontegg server, but you can provide it manually.
# Copy and paste the first key from the response (not the whole array):
# {keys: [{__KEY__}]}
FRONTEGG_JWT_PUBLIC_KEY='{"kty":"RSA","kid":"...'

# When `true`, the initial props will not refresh the access token if it's still valid.
# This option saves the time of refreshing the token on the server side.
DISABLE_INITIAL_PROPS_REFRESH_TOKEN='true'

# Enable secure JWT by removing the signature from the JWT token.
# To enable this feature, you need to provide {@link EnvVariables.FRONTEGG_CLIENT_SECRET}
FRONTEGG_SECURE_JWT_ENABLED='false'

# Accept the hosted login authorization code on the FRONTEGG_APP_URL itself, in addition to
# the `/oauth/callback` route. Needed for flows that are started outside the application,
# like impersonation, which redirect to the application URL configured in the Frontegg portal.
# Requires FRONTEGG_SECURE_JWT_ENABLED, and the application URL configured in the Frontegg portal
# must be identical to FRONTEGG_APP_URL.
FRONTEGG_HOSTED_LOGIN_CALLBACK_ON_APP_URL='false'

# The Frontegg Hosted Login URL used to redirect the user to the Frontegg login page.
# Set to 'true' to enable the hosted login feature.
FRONTEGG_HOSTED_LOGIN='true'
```

## 文档

### API 参考

访问 [前置数据](https://docs.frontegg.com/) 用于完整文件.

### Frontegg 提供方选项

传递秒参数到 `withFronteggApp` 函数在 `_app.ts` 要自定义的文件 Frontegg 图书馆.

```tsx
// ./pages/_app.tsx

import { withFronteggApp } from '@frontegg/nextjs/pages';

function CustomApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

export default withFronteggApp(CustomApp, {
  hostedLoginBox: true,
  /**
   * Frontegg options for customizations
   */
});
```

### 获取会议

在服务器侧需要 AccessToken 的任何页面,您都可以使用 :

```tsx
import { GetServerSideProps } from 'next';
import { getSession } from '@frontegg/nextjs/pages';

export default function MyPage({ products }) {
  return (
    <div>
      <h1>My Page</h1>
      {products}
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const session = await getSession(context.req);
  if (session) {
    const { data } = await fetch('{external}/product', {
      headers: {
        Authorization: 'bearer ' + session.accessToken,
      },
    });
    return { props: { products: data } };
  }

  return { props: { products: [] } };
};
```

### 与届会

与SSRSession HOC相通,如果不登录在 :

```tsx
import { GetServerSideProps } from 'next';
import { withSSRSession } from '@frontegg/nextjs/pages';

export default function MyPage({ products }) {
  return (
    <div>
      <h1>My Page</h1>
      {products}
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = withSSRSession(
  async (context, session) => {
    const { data } = await fetch('{external}/product', {
      headers: {
        Authorization: 'bearer ' + session.accessToken,
      },
    });
    return { props: { products: data } };
  }
);
```

## Next.js (AppDir 架构)

### 正在包装您的应用程序

```tsx
// ./app/layout.tsx
import { FronteggAppProvider } from '@frontegg/nextjs/app';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <FronteggAppProvider hostedLoginBox>
      <html>
        <head></head>
        <body>{children}</body>
      </html>
    </FronteggAppProvider>
  );
}
```

### 路径

```tsx
// ./app/[...frontegg-router]/page.tsx

export { FronteggAppRouter as default } from '@frontegg/nextjs/app';
```

### 服务器组件

通知此会话不属于状态, 因此不会在变化时触发 ui 更改

```tsx
// ./app/ServerComponent.tsx
import { getSession } from "@frontegg/nextjs/app";

export const ServerComponent = async () => {
  const session = await getSession();

  return <pre>{JSON.stringify(session, null, 2)}</pre>;
};

```

### 客户部分

```tsx
// ./app/ClientComponent.tsx
"use client";
import { useAuth, useLoginWithRedirect } from "@frontegg/nextjs";
import { useRouter } from 'next/navigation'

export const ClientComponent = ({ baseUrl }: { baseUrl?: string }) => {
  const { user, isAuthenticated } = useAuth();
  const router = useRouter();
  const loginWithRedirect = useLoginWithRedirect();

  const logout = () => {
    router.replace('/account/logout')
  };

  return (
    <div className="App">
      {isAuthenticated ? (
        <div>
          <div>
            <img src={user?.profilePictureUrl} alt={user?.name} />
          </div>
          <div>
            <span>Logged in as: {user?.name}</span>
          </div>
          <div>
            <button onClick={() => alert(user?.accessToken)}>
              What is my access token?
            </button>
          </div>
          <div>
            <button onClick={() => logout()}>Click to logout</button>
          </div>
        </div>
      ) : (
        <div>
          <button onClick={() => loginWithRedirect()}>Click me to login</button>
        </div>
      )}
    </div>
  );
};
```

### 页次

```tsx
// ./app/page.tsx
import { ClientComponent } from "./client";
import { ServerComponent } from "./server";

export default function MainPage() {
  return (
    <div>
      <h3>Next JS application with frontegg</h3>
      {/* @ts-ignore ignore server components error with typescript*/}
      <ServerComponent />
    </div>
  );
}
```

并保留前置蛋米德尔软件在./pages/api/frontegg/\[.frontegg-middleware\].ts内,如前所示

## Next.js 中间软件的使用

防止未经认证的用户访问所有路由,使用 [下一个.js 中间软件](https://nextjs.org/docs/advanced-features/middleware)。 。 。 .

**注:如果你在12.2之前使用Middleware,请参见 [升级指南](https://nextjs.org/docs/messages/middleware-upgrade-guide)。 。 。 .**

```ts
// /middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getSessionOnEdge, shouldByPassMiddleware, redirectToLogin } from '@frontegg/nextjs/edge';

export const middleware = async (request: NextRequest) => {
  const pathname = request.nextUrl.pathname;

  if (shouldByPassMiddleware(pathname)) {
    return NextResponse.next();
  }

  const session = await getSessionOnEdge(request);
  if (!session) {
    return redirectToLogin(pathname);
  }
  return NextResponse.next();
};

export const config = {
  matcher: '/(.*)',
};
```

## 用动词快速启动前蛋

用 Vercel 点击来方便克隆前置应用程序样本并部署 [这里](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Ffrontegg%2Ffrontegg-nextjs%2Ftree%2Fmaster%2Fdemos%2Fquick-starter-demo&env=FRONTEGG_BASE_URL,FRONTEGG_CLIENT_ID,FRONTEGG_ENCRYPTION_PASSWORD&envDescription=Used%20to%20connect%20to%20your%20frontegg%20account%20and%20encrypt%20the%20frontegg%20session%20cookie&envLink=https%3A%2F%2Fdocs.frontegg.com%2Fdocs%2Fnextjs-12-13-ssr-hosted-login%23step-4-setup-environment&project-name=my-frontegg-app&repository-name=my-frontegg-app&demo-title=Authentication&demo-description=Basic%20application%20with%20Frontegg%20authentication%20&demo-url=https%3A%2F%2Fmy-frontegg-app.vercel.app&demo-image=https%3A%2F%2Ffronteggprodeustorage.blob.core.windows.net%2Fpublic-vendor-assets%2F4f091b2c-5755-4145-a313-10d9a530276f%2Fassets%2Flogo-fa2b14b1-d07d-49fd-8c24-a51f5d92c4d7.png)

## 警卫

这个 `@frontegg/nextjs` SDK被积极维护,其依赖性被保存在流,补丁版本上. 补丁版本的过渡依赖通过 `resolutions` 字段中 `package.json`。 。 。 .

为了保护您的应用程序, 总是使用最新的发布 :

```bash
yarn add @frontegg/nextjs@latest
# or
npm install @frontegg/nextjs@latest
```

### 报告脆弱性

如果您发现SDK中存在安全漏洞,请通过电子邮件负责报告 **[安全性@ frondegg.com](mailto:security@frontegg.com)**请不要为安全报告打开一个公开的 GitHub 问题 .

## 常见问题

### 如何安装 @frontegg/nextjs？

在项目目录运行 npm install @frontegg/nextjs，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^16\.9\.0 \|\| ^17\.0\.0 \|\| ^18\.0\.0 \|\| ^19\.0\.0）、react-dom（^16\.9\.0 \|\| ^17\.0\.0 \|\| ^18\.0\.0 \|\| ^19\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @frontegg/nextjs 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @frontegg/nextjs 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @frontegg/nextjs 可以商用吗？

@frontegg/nextjs 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @frontegg/nextjs 的下载量有多少？

根据 npm 官方下载统计，@frontegg/nextjs 在 2026/10/16 – 2026/11/14 这 30 天内被下载 43,252 次，日均约 1,442 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @frontegg/nextjs 还在维护吗？

最新版本 9\.2\.14 发布于 2026/09/29（1 个月前）；至今共发布 714 个版本，其中过去 12 个月发布了 12 个；首次发布于 2021/08/11。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

