
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 引导 换句话说.
-
环绕默认导出方式
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 }); -
在下方创建前置中间软件的文件
./pages/api/frontegg/[...frontegg-middleware].ts数字 :// ./pages/api/frontegg/[...frontegg-middleware].ts export { fronteggMiddleware as default } from '@frontegg/nextjs/middleware'; -
在下面为前置路由器创建占位符页面
./pages/[...frontegg-router].tsx数字 :// ./pages/[...frontegg-router].tsx export { FronteggRouter as default, FronteggRouterProps as getServerSideProps, } from '@frontegg/nextjs/pages';
使用自定义域的 Vercel 平台
- 访问
https://vercel.com/[ACCOUNT_ID]/[PROJECT_ID]/settings/environment-variables - 添加
FRONTEGG_APP_URL每个Vercel环境的环境变量
开始
创建 Frontegg 工作空间
导航到 Frontegg 门户设置如果您没有申请 注册后遵循整合步骤.
下一步, 在“ 设置” 页的“ 域” 标签下配置您的应用程序中的“ 全部来源 ” :
- http://localhost:3:00/用于发展环境
- https://my-company-domain.com (中文(中国大陆) ) //用于生产环境
复制客户端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 问题 .