
npm install @frontegg/nextjsFrontegg 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.
- Installation
- Create new NextJS project
- Add to existing project
- Using Vercel platform with custom domain
- Getting Started
- Create Frontegg workspace
- Setup environment
- Documentation
- API Reference
- Frontegg Provider Options
- getSession
- withSSRSession
- Next.js middlewares usage
- for more visit
To Add Frontegg to your existing Next.JS project, follow below steps:
Use package manager to install Frontegg Next.JS library.
``bash`
npm install --save @frontegg/nextjs
or
`bash`
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:
`tsx
// ./pages/_app.tsx
import { withFronteggApp } from "@frontegg/nextjs/pages";
function CustomApp({ Component, pageProps }: AppProps) {
return
}
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:
`tsx
// ./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:
`tsx
// ./pages/[...frontegg-router].tsx
export {
FronteggRouter as default,
FronteggRouterProps as getServerSideProps,
} from '@frontegg/nextjs/pages';
`
1. Visit https://vercel.com/[ACCOUNT_ID]/[PROJECT_ID]/settings/environment-variablesFRONTEGG_APP_URL
2. Add environment variable for each Vercel Environment
!vercel-settings-pages
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 :
- http://localhost:3000 // for development environments
- https://my-company-domain.com // for production environments
Copy ClientID, Frontegg Domain from "Settings" page, You'll need these values in the next step.
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:
`dotenvThe AppUrl is used to tell Frontegg your application hostname
FRONTEGG_APP_URL='http://localhost:3000'
and ServerComponents. environment variable., the initial props will not refresh the access token if it's still valid.Documentation
$3
Visit Frontegg Docs for the full documentation.
$3
Pass seconds argument to
withFronteggApp function in _app.ts file to customize
Frontegg library.`tsx
// ./pages/_app.tsximport { withFronteggApp } from '@frontegg/nextjs/pages';
function CustomApp({ Component, pageProps }: AppProps) {
return ;
}
export default withFronteggApp(CustomApp, {
hostedLoginBox: true,
/**
* Frontegg options for customizations
*/
});
`$3
For any pages that required AccessToken in Server Side, you can use:
`tsx
import { GetServerSideProps } from 'next';
import { getSession } from '@frontegg/nextjs/pages';export default function MyPage({ products }) {
return (
My Page
{products}
);
}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: [] } };
};
`$3
withSSRSession HOC can be used to automatic redirect users to login screen if not logged in:
`tsx
import { GetServerSideProps } from 'next';
import { withSSRSession } from '@frontegg/nextjs/pages';export default function MyPage({ products }) {
return (
My Page
{products}
);
}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)
$3
`tsx
// ./app/layout.tsx
import { FronteggAppProvider } from '@frontegg/nextjs/app';export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
`$3
`tsx
// ./app/[...frontegg-router]/page.tsxexport { FronteggAppRouter as default } from '@frontegg/nextjs/app';
`
$3
notice that this session is not part of the state and therefore won't trigger ui changes when it changes
`tsx
// ./app/ServerComponent.tsx
import { getSession } from "@frontegg/nextjs/app";export const ServerComponent = async () => {
const session = await getSession();
return
{JSON.stringify(session, null, 2)};
};`$3
`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 (
{isAuthenticated ? (

Logged in as: {user?.name}
) : (
)}
);
};
`$3
`tsx
// ./app/page.tsx
import { ClientComponent } from "./client";
import { ServerComponent } from "./server";export default function MainPage() {
return (
Next JS application with frontegg
{/ @ts-ignore ignore server components error with typescript/}
);
}
`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.
`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: '/(.*)',
};
``To easily clone frontegg app sample and deploy with Vercel click here