@frontegg/nextjs

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

alt text

原始使用文档
文档目录22 节
  1. Table of Contents
  2. Installation
  3. Add Frontegg to Next.JS project
  4. Using Vercel platform with custom domain
  5. Getting Started
  6. Create Frontegg workspace
  7. Setup environment
  8. Documentation
  9. API Reference
  10. Frontegg Provider Options
  11. getSession
  12. withSSRSession
  13. Next.js (AppDir architecture)
  14. wrapping your application
  15. routing
  16. server component
  17. client component
  18. Page
  19. Next.js middlewares usage
  20. Quick start frontegg with vercel
  21. Security
  22. Reporting a vulnerability

alt text

Frontegg is a web platform where SaaS companies can set up their fully managed, scalable and brand aware - SaaS features and integrate them into their SaaS portals in up to 5 lines of code.

Table of Contents

Installation

Add Frontegg to Next.JS project

To Add Frontegg to your existing Next.JS project, follow below steps:

Use package manager to install Frontegg Next.JS library.

  npm install --save @frontegg/nextjs

or

  yarn add --save @frontegg/nextjs

If you're using the App Directory architecture, you can skip the following Pages architecture steps and refer to the AppDir guide instead.

  1. Wrap the default export with withFronteggApp in ./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. Create files for frontegg middleware under ./pages/api/frontegg/[...frontegg-middleware].ts:

    // ./pages/api/frontegg/[...frontegg-middleware].ts
    
    export { fronteggMiddleware as default } from '@frontegg/nextjs/middleware';
    
  3. Create placeholder pages for frontegg router under ./pages/[...frontegg-router].tsx:

    // ./pages/[...frontegg-router].tsx
    
    export {
      FronteggRouter as default,
      FronteggRouterProps as getServerSideProps,
    } from '@frontegg/nextjs/pages';
    

Using Vercel platform with custom domain

  1. Visit https://vercel.com/[ACCOUNT_ID]/[PROJECT_ID]/settings/environment-variables
  2. Add FRONTEGG_APP_URL environment variable for each Vercel Environment vercel-settings-pages

Getting Started

Create Frontegg workspace

Navigate to Frontegg Portal Settings, If you don't have application follow integration steps after signing up.

Next, configure the "Allowed Origins" in your application under "Domain" tab of the "Settings" page :

Copy ClientID, Frontegg Domain from "Settings" page, You'll need these values in the next step.

Setup environment

To set up your Next.js application to communicate with Frontegg, you have to create a new file named .env.local under your root project directory, this file will be used to store environment variables that will be used, configuration options:

# 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'

Documentation

API Reference

Visit Frontegg Docs for the full documentation.

Frontegg Provider Options

Pass seconds argument to withFronteggApp function in _app.ts file to customize Frontegg library.

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

getSession

For any pages that required AccessToken in Server Side, you can use:

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: [] } };
};

withSSRSession

withSSRSession HOC can be used to automatic redirect users to login screen if not logged in:

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 architecture)

wrapping your application

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

routing

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

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

server component

notice that this session is not part of the state and therefore won't trigger ui changes when it changes

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

client component

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

Page

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

also keep fronteggMiddleware inside ./pages/api/frontegg/[...frontegg-middleware].ts as shown before

Next.js middlewares usage

To prevent access unauthenticated user to all routes, use Next.js middlewares.

Note: If you were using Middleware prior to 12.2, please see the upgrade guide.

// /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: '/(.*)',
};

Quick start frontegg with vercel

To easily clone frontegg app sample and deploy with Vercel click here

Security

The @frontegg/nextjs SDK is actively maintained, and its dependencies are kept on current, patched versions. Patched versions of transitive dependencies are enforced through the resolutions field in the root package.json.

To keep your application protected, always use the latest release:

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

Reporting a vulnerability

If you discover a security vulnerability in this SDK, please report it responsibly by emailing [email protected]. Please do not open a public GitHub issue for security reports.

版本与发布记录

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