8.0.18 • Published 22 days ago

@frontegg/nextjs v8.0.18

Weekly downloads
-
License
MIT
Repository
github
Last release
22 days ago

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.

You are reading v6 docs, v7 docs under construction, Visit the latest changelog for migration from v6.

Table of Contents

Installation

Add Frontegg to Next.JS project

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

  1. Use package manager to install Frontegg Next.JS library.

      npm install --save @frontegg/nextjs

    or

      yarn add --save @frontegg/nextjs
  2. 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, {
     hostedLoginBox: true
     });
  3. 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';
  4. 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 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
FRONTEGG_CLIENT_ID='{YOUR_APPLICATION_CLIENT_ID}'

# The statless session encruption password, used to encrypt
# 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 statless session cookie name
FRONTEGG_COOKIE_NAME='fe_session'

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 13

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

8.0.18

22 days ago

8.0.17

1 month ago

8.0.16

1 month ago

8.0.15

2 months ago

8.0.14

2 months ago

8.0.13

3 months ago

8.0.12

3 months ago

8.0.11

4 months ago

8.0.10

4 months ago

8.0.9

5 months ago

7.0.13

11 months ago

7.0.18

9 months ago

7.0.19

8 months ago

7.0.16

10 months ago

7.0.17

9 months ago

7.0.14

11 months ago

7.0.15

10 months ago

8.0.8

5 months ago

8.0.5

7 months ago

8.0.4

7 months ago

8.0.7

6 months ago

8.0.6

7 months ago

8.0.1

8 months ago

8.0.3

7 months ago

8.0.2

8 months ago

7.0.12

11 months ago

7.0.11

11 months ago

7.0.10

12 months ago

7.0.8

1 year ago

7.0.7

1 year ago

7.0.6

1 year ago

7.0.5

1 year ago

7.0.9

12 months ago

7.0.4

1 year ago

6.7.19

1 year ago

6.7.20

1 year ago

7.0.0

1 year ago

7.0.3

1 year ago

7.0.2

1 year ago

7.0.1

1 year ago

6.7.18

1 year ago

6.7.12

1 year ago

6.7.13

1 year ago

6.7.14

1 year ago

6.7.15

1 year ago

6.7.16

1 year ago

6.7.17

1 year ago

6.7.10

1 year ago

6.7.11

1 year ago

6.7.2

2 years ago

6.7.4

1 year ago

6.7.3

1 year ago

6.7.6

1 year ago

6.7.5

1 year ago

6.7.8

1 year ago

6.7.7

1 year ago

6.7.9

1 year ago

6.7.0

2 years ago

6.7.1

2 years ago

6.5.0

2 years ago

6.6.0

2 years ago

5.10.0

2 years ago

6.1.0

2 years ago

6.2.0

2 years ago

6.3.0

2 years ago

6.4.0

2 years ago

5.8.0

2 years ago

5.9.0

2 years ago

4.0.21

2 years ago

4.0.20

2 years ago

4.0.23

2 years ago

4.0.22

2 years ago

5.4.1

2 years ago

5.4.0

2 years ago

5.5.0

2 years ago

5.6.0

2 years ago

5.7.0

2 years ago

5.1.1

2 years ago

4.0.19

2 years ago

5.1.0

2 years ago

4.0.18

2 years ago

5.2.0

2 years ago

5.3.0

2 years ago

4.0.17

2 years ago

4.0.16

2 years ago

4.0.15

2 years ago

4.0.14

2 years ago

4.0.13

2 years ago

4.0.12

2 years ago

4.0.9

2 years ago

4.0.10

2 years ago

4.0.11

2 years ago

4.0.5

2 years ago

4.0.4

2 years ago

4.0.7

2 years ago

4.0.6

2 years ago

4.0.3

2 years ago

4.0.8

2 years ago

4.0.1

2 years ago

4.0.2

2 years ago

3.0.21

2 years ago

3.0.20

2 years ago

3.0.18

3 years ago

3.0.19

3 years ago

3.0.17

3 years ago

3.0.16

3 years ago

3.0.12

3 years ago

3.0.10

3 years ago

3.0.11

3 years ago

3.0.14

3 years ago

3.0.15

3 years ago

3.0.9

3 years ago

3.0.8

3 years ago

3.0.4

3 years ago

3.0.7

3 years ago

3.0.6

3 years ago

3.0.5

3 years ago

3.0.3

3 years ago

3.0.2

3 years ago

3.0.1

3 years ago

3.0.0-alpha.13

3 years ago

3.0.0-alpha.12

3 years ago

3.0.0-alpha.11

3 years ago

2.8.22

3 years ago

2.8.21

3 years ago

2.8.20

3 years ago

2.8.19

3 years ago