Kinde Auth SDK for NextJS

repository·main·Indexed 41 days ago

https://github.com/kinde-oss/kinde-auth-nextjs

Official SDK for integrating Kinde authentication into Next.js applications. Version 2.13.1 provides tools for secure user management, access control, and session handling. Key features include the handleAuth function for managing auth endpoints, protectPage and protectApi higher-order functions for enforcing roles and permissions, and the KindeProvider and useKindeAuth hook for accessing authentication state, feature flags, and user claims in client components.

Tokens
11K
Snippets
34
Records
44
Agent score
50%

What's inside Kinde

  1. Set up the Kinde NextJS Playground

    main

    To experiment with the SDK in a local environment, you can run the playground. This process clones the NextJS app router starter kit into a /playground directory and links the SDK locally using npm link.

    1. Prepare the playground:
      npm run dev:prepare
    2. Configure credentials: Add your Kinde credentials to the .env.local file generated inside the /playground directory.
    3. Start the playground:
      npm run dev

    The playground will be available at http://localhost:3000.

    npm run dev:prepare
    # Add credentials to /playground/.env.local
    npm run dev
  2. Configure session persistence

    main

    The SessionManager allows you to toggle between persistent and non-persistent sessions via the persistent property.

    • Persistent (true): Cookies are set with a maxAge of TWENTY_NINE_DAYS (29 days).
    • Non-persistent (false): Cookies are treated as session cookies (no maxAge specified, meaning they expire when the browser session ends).

    You can set this during initialization via the options object or by modifying the property on the returned instance.

  3. Configure Kinde environment variables

    main

    The @kinde-oss/kinde-auth-nextjs SDK is configured via environment variables. Many variables support both standard and NEXT_PUBLIC_ prefixed versions to allow access from both the server and the client side.

    Core Authentication Variables

    • KINDE_CLIENT_ID: Your Kinde client ID.
    • KINDE_CLIENT_SECRET: Your Kinde client secret (Server-side only).
    • KINDE_ISSUER_URL: The Kinde issuer URL.
    • KINDE_SCOPE: Space-separated list of scopes (defaults to openid profile email offline).
    • KINDE_AUDIENCE: Space-separated list of audiences.

    Redirect and URL Configuration

    • KINDE_SITE_URL or NEXT_PUBLIC_KINDE_SITE_URL: The base URL of your application.
    • KINDE_AUTH_API_PATH or NEXT_PUBLIC_KINDE_AUTH_API_PATH: The path for Kinde auth routes (defaults to /api/auth).
    • KINDE_POST_LOGIN_REDIRECT_URL or KINDE_POST_LOGIN_URL_REDIRECT_URL: Where to redirect users after a successful login.
    • KINDE_POST_LOGOUT_REDIRECT_URL: Where to redirect users after logout.
    • KINDE_POST_LOGIN_ALLOWED_URL_REGEX: A regex string to validate allowed post-login redirect URLs.
    • KINDE_COOKIE_DOMAIN: The domain for Kinde cookies.

    Custom Route Overrides

    You can override specific Kinde auth routes using these environment variables:

    • KINDE_AUTH_LOGIN_ROUTE (default: login)
    • KINDE_AUTH_LOGOUT_ROUTE (default: logout)
    • KINDE_AUTH_REGISTER_ROUTE (default: register)
    • KINDE_AUTH_CREATEORG_ROUTE (default: create_org)
    • KINDE_AUTH_HEALTH_ROUTE (default: health)
    • KINDE_AUTH_SETUP_ROUTE (default: setup)
    • KINDE_AUTH_PORTAL_ROUTE (default: portal)
    • KINDE_AUTH_ENDSESSION_ROUTE (default: end_session)

    Note: Custom routes must only contain alphanumeric characters, underscores, or hyphens (^[a-zA-Z0-9_-]+$).

  4. Wrap your application with KindeProvider

    main

    To access authentication state and methods in your client components, you must wrap your application (or a specific part of your component tree) with the KindeProvider. This provider handles the session check and makes user data, tokens, and feature flags available via context.

    import { KindeProvider } from '@kinde-oss/kinde-auth-nextjs/react';
    
    export default function App({ children }) {
      return (
        <KindeProvider>
          {children}
        </KindeProvider>
      );
    }
  5. Protect Next.js pages with protectPage

    main

    Use the protectPage higher-order function to wrap your Next.js page components. It enforces authentication and authorization (roles and permissions) before rendering the component. If the user is not authenticated or lacks the required authorization, they are automatically redirected to the Kinde authentication URL.

    Configuration Options:

    • postLoginRedirectURL (string): The URL to redirect to after a successful login. If provided as a relative path (starting with /), it is automatically prefixed with your KINDE_SITE_URL.
    • orgCode (string): The organization code for multi-tenant applications.
    • roles (string[]): An array of required role names. The user must have at least one of these roles.
    • permissions (string | string[]): A single permission string or an array of permission strings. The user must possess at least one of the specified permissions.
    import { protectPage } from "@kinde-oss/kinde-auth-nextjs";
    
    const MyPage = (props) => {
      return <div>Protected Content</div>;
    };
    
    export default protectPage(MyPage, {
      roles: ["admin"],
      permissions: ["read:reports"],
      postLoginRedirectURL: "/dashboard"
    });
  6. Access session data with getKindeServerSession

    main

    In Next.js Pages Router applications, use getKindeServerSession(req, res) to obtain a session handler object. This handler provides methods to retrieve user information, tokens, permissions, and feature flags from the current session.

    Important Compatibility Note:

    • This method is designed exclusively for the Pages Router.
    • It is not compatible with the App Router. App Router users should use the refreshData method in useKindeBrowserClient instead.
    import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs";
    
    export async function getServerSideProps({ req, res }) {
      const { getKindeServerSession } = await getKindeServerSession(req, res);
      
      const user = await getUser();
      const isAuthenticated = await isAuthenticated();
      const accessToken = await getAccessToken();
    
      return {
        props: {
          user,
          isAuthenticated,
        },
      };
    }
  7. Retrieve specific claims using getClaimFactory

    main

    In Next.js environments, you can use getClaimFactory to create a function that retrieves specific claims (such as user roles, email, or custom attributes) from either the access_token or the id_token.

    To use it, pass the Next.js req (Request) and res (Response) objects to the factory. The returned function is asynchronous and accepts the name of the claim and an optional type specifying which token to pull the claim from.

    import { getClaimFactory } from '@kinde-oss/kinde-auth-nextjs';
    
    // In a Next.js API route or Server-side function
    export default async function handler(req, res) {
      const getClaim = getClaimFactory(req, res);
      
      // Retrieve a claim from the id_token (default)
      const userEmail = await getClaim('email');
      
      // Retrieve a claim from the access_token
      const userRole = await getClaim('role', 'access_token');
    
      if (userEmail) {
        console.log('User email:', userEmail.value);
      }
    }
  8. Use Kinde React hooks and providers

    main

    The @kinde-oss/kinde-auth-nextjs SDK provides hooks and a provider to manage authentication state and browser client access within your React components.

    • KindeProvider: A context provider that must wrap your application to enable Kinde authentication features.
    • useKindeAuth: A hook to access the current authentication state (e.g., whether a user is logged in, user details, etc.).
    • useKindeBrowserClient: A hook to access the Kinde browser client for advanced client-side operations.
    import { KindeProvider, useKindeAuth } from "@kinde-oss/kinde-auth-nextjs";
    
    function App() {
      return (
        <KindeProvider>
          <MyComponent />
        </KindeProvider>
      );
    }
    
    function MyComponent() {
      const { isAuthenticated, user } = useKindeAuth();
      // ...
    }
  9. Retrieve user information and tokens

    main

    The useKindeAuth hook provides several properties to access the authenticated user's data and security tokens:

    • user: The user object containing profile information.
    • isAuthenticated: A boolean indicating if a user is currently logged in.
    • isLoading: A boolean indicating if the initial session check is in progress.
    • accessToken: The access token.
    • idToken: The ID token.
    • getAccessToken(), getToken(): Methods to retrieve the access token.
    • getIdToken(), getIdTokenRaw(): Methods to retrieve the ID token.
    • getUser(), getUserOrganizations(): Methods to retrieve user and organization data.