npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@frontegg/nextjs

v9.2.1

Published

![alt text](https://raw.githubusercontent.com/frontegg/frontegg-nextjs/master/logo.png)

Downloads

23,790

Readme

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:

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 :

  • 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.

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'

# 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