@frontegg/nextjs

中文文档
9.2.14发布于 2026/09/29MITTypeScriptESM + CJS近 30 天下载 4.3万

alt text

中文使用文档
文档目录22 节
  1. 目录
  2. 安装
  3. 将 Frontegg 添加到 Next.JS 项目
  4. 使用自定义域的 Vercel 平台
  5. 开始
  6. 创建 Frontegg 工作空间
  7. 设置环境
  8. 文档
  9. API 参考
  10. Frontegg 提供方选项
  11. 获取会议
  12. 与届会
  13. Next.js (AppDir 架构)
  14. 正在包装您的应用程序
  15. 路径
  16. 服务器组件
  17. 客户部分
  18. 页次
  19. Next.js 中间软件的使用
  20. 用动词快速启动前蛋
  21. 警卫
  22. 报告脆弱性

alt text

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

目录

安装

将 Frontegg 添加到 Next.JS 项目

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

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

  npm install --save @frontegg/nextjs

或者说

  yarn add --save @frontegg/nextjs

如果您使用 App 目录架构, 您可以跳过以下 Pages 架构步骤并参考 AppDir 引导 换句话说.

  1. 环绕默认导出方式 withFronteggApp 内 ./pages/_app.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数字 :

    // ./pages/api/frontegg/[...frontegg-middleware].ts
    
    export { fronteggMiddleware as default } from '@frontegg/nextjs/middleware';
    
  3. 在下面为前置路由器创建占位符页面 ./pages/[...frontegg-router].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

开始

创建 Frontegg 工作空间

导航到 Frontegg 门户设置如果您没有申请 注册后遵循整合步骤.

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

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

设置环境

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

# 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 参考

访问 前置数据 用于完整文件.

Frontegg 提供方选项

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

// ./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 的任何页面,您都可以使用 :

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相通,如果不登录在 :

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 架构)

正在包装您的应用程序

// ./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>
  );
}

路径

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

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

服务器组件

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

// ./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>;
};

客户部分

// ./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>
  );
};

页次

// ./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 中间软件。 。 。 .

注:如果你在12.2之前使用Middleware,请参见 升级指南。 。 。 .

// /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 点击来方便克隆前置应用程序样本并部署 这里

警卫

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

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

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

报告脆弱性

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

版本与发布记录

@frontegg/nextjs 共发布 714 个版本,首次发布于 2021/08/11;过去 12 个月发布了 12 个版本。

版本发布日期距今
9.2.14latest2026/09/291 个月前
9.2.14-alpha.36564855569next2026/09/291 个月前
9.2.14-alpha.343306791312026/09/092 个月前
9.2.14-alpha.294109297362026/07/154 个月前
9.2.14-alpha.293678101972026/07/154 个月前
9.2.132026/03/048 个月前

其他发布通道:alpha → 9.2.6-alpha.15312015691,next → 9.2.14-alpha.36564855569。

关于 @frontegg/nextjs 的常见问题

如何安装 @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 和提交记录判断。