Helper class to integrate Fief authentication with Next.js.

Example: Basic

import { Fief, FiefUserInfo } from '@fief/fief';
import { FiefAuth, IUserInfoCache } from '@fief/fief/nextjs';

export const SESSION_COOKIE_NAME = "user_session";

const fiefClient = new fief.Fief({
baseURL: 'https://example.fief.dev',
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
});

export const fiefAuth = new FiefAuth({
client: fiefClient,
sessionCookieName: SESSION_COOKIE_NAME,
redirectURI: 'http://localhost:3000/auth-callback',
logoutRedirectURI: 'http://localhost:3000',
userInfoCache: new UserInfoCache(),
});

Constructors

Properties

accessTokenHeaderName: string
accessTokenInfoHeaderName: string
apiForbiddenResponse: ((req, res) => Promise<void>)

Type declaration

    • (req, res): Promise<void>
    • Parameters

      • req: NextApiRequest
      • res: NextApiResponse

      Returns Promise<void>

apiUnauthorizedResponse: ((req, res) => Promise<void>)

Type declaration

    • (req, res): Promise<void>
    • Parameters

      • req: NextApiRequest
      • res: NextApiResponse

      Returns Promise<void>

client: Fief
fiefAuth: FiefAuth<IncomingMessage>
fiefAuthEdge: FiefAuth<NextRequest>
forbiddenPath: string
loginPath: string
logoutPath: string
logoutRedirectURI: string
redirectPath: string
redirectURI: string
returnToCookieName: string
returnToDefault: string
sessionCookieName: string
userIdHeaderName: string

Methods

  • Return an API middleware to authenticate an API route.

    Type Parameters

    • T

    Parameters

    • route: FiefNextApiHandler<T>

      Your API route handler.

    • authenticatedParameters: AuthenticateRequestParameters = {}

      Optional parameters to apply when authenticating the request.

    Returns FiefNextApiHandler<T>

    An API handler.

    See

    Next.js API Routes

    Example: Basic

    import { fiefAuth } from "../../fief"

    export default fiefAuth.authenticated(function handler(req, res) {
    res.status(200).json(req.user);
    });

    Example: Required scope

    import { fiefAuth } from "../../fief"

    export default fiefAuth.authenticated(function handler(req, res) {
    res.status(200).json(req.user);
    }, { scope: ['required_scope'] });

    Example: Minimum ACR level

    import { fiefAuth } from "../../fief"

    export default fiefAuth.authenticated(function handler(req, res) {
    res.status(200).json(req.user);
    }, { acr: FiefACR.LEVEL_ONE });

    Example: Required permissions

    import { fiefAuth } from "../../fief"

    export default fiefAuth.authenticated(function handler(req, res) {
    res.status(200).json(req.user);
    }, { permissions: ['castles:create'] });
  • Return the access token information set in headers by the Fief middleware, or null if not authenticated.

    This function is suitable for server-side rendering in Next.js.

    Parameters

    • Optional req: IncomingMessage

      Next.js request object. Required for older versions of Next.js not supporting the headers() function.

    Returns null | FiefAccessTokenInfo

    he access token information, or null if not available.

  • Return the user ID set in headers by the Fief middleware, or null if not authenticated.

    This function is suitable for server-side rendering in Next.js.

    Parameters

    • Optional req: IncomingMessage

      Next.js request object. Required for older versions of Next.js not supporting the headers() function.

    Returns null | string

    The user ID, or null if not available.

  • Fetch the user information object from the Fief API, if access token is available.

    This function is suitable for server-side rendering in Next.js.

    Parameters

    • Optional req: IncomingMessage

      Next.js request object. Required for older versions of Next.js not supporting the headers() function.

    • refresh: boolean = false

      If true, the user information will be refreshed from the Fief API. Otherwise, Next.js fetch cache will be used.

    Returns Promise<null | FiefUserInfo>

    The user information, or null if access token is not available.

  • Return a Next.js middleware to control authentication on the specified paths.

    Parameters

    • pathsConfig: PathConfig[]

      A list of paths matchers with their authentication parameters.

    Returns ((request) => Promise<NextResponse<unknown>>)

    A Next.js middleware function.

      • (request): Promise<NextResponse<unknown>>
      • Parameters

        • request: NextRequest

        Returns Promise<NextResponse<unknown>>

    See

    Next.js Middleware

    Example

    import type { NextRequest } from 'next/server'

    import { fiefAuth } from './fief'

    const authMiddleware = fiefAuth.middleware([
    {
    matcher: '/private',
    parameters: {},
    },
    {
    matcher: '/app/:path*',
    parameters: {},
    },
    {
    matcher: '/scope',
    parameters: {
    scope: ['required_scope'],
    },
    },
    {
    matcher: '/acr',
    parameters: {
    acr: FiefACR.LEVEL_ONE,
    },
    },
    {
    matcher: '/permission',
    parameters: {
    permissions: ['castles:create'],
    },
    },
    ]);

    export async function middleware(request: NextRequest) {
    return authMiddleware(request);
    };