CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-next-auth

Authentication library for Next.js applications with support for OAuth, email, and credentials authentication

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

react-integration.mddocs/

React Client Integration

React hooks and components for managing authentication state and user interactions in client-side components. Provides seamless integration with React applications for sign-in/sign-out flows and session management.

Capabilities

Session Provider

React context provider that makes session data available throughout the component tree and manages session state synchronization.

/**
 * Provider component that wraps the app to make session data globally available
 * @param props - Configuration options for session management
 * @returns JSX provider component
 */
function SessionProvider(props: SessionProviderProps): JSX.Element;

interface SessionProviderProps {
  /** React children components */
  children: React.ReactNode;
  /** Optional initial session (from getServerSideProps) */
  session?: Session | null;
  /** Base URL for NextAuth.js API (auto-detected if not provided) */
  baseUrl?: string;
  /** Base path for NextAuth.js API routes (default: "/api/auth") */
  basePath?: string;
  /** Refetch session interval in seconds (0 to disable) */
  refetchInterval?: number;
  /** Refetch session when window gains focus (default: true) */
  refetchOnWindowFocus?: boolean;
  /** Refetch session when offline (default: true) */
  refetchWhenOffline?: false;
}

Usage Example:

// pages/_app.tsx (Pages Router)
import { SessionProvider } from "next-auth/react";
import type { AppProps } from "next/app";

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}: AppProps) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}

// app/layout.tsx (App Router)
import { SessionProvider } from "next-auth/react";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <SessionProvider>
          {children}
        </SessionProvider>
      </body>
    </html>
  );
}

Use Session Hook

React hook that provides access to the current user session and loading state.

/**
 * React hook for accessing session data and authentication state
 * @param options - Hook configuration options
 * @returns Session context value with data, status and update function
 */
function useSession<R extends boolean>(
  options?: UseSessionOptions<R>
): SessionContextValue<R>;

interface UseSessionOptions<R extends boolean> {
  /** Redirect to sign-in page if user is not authenticated */
  required?: R;
  /** Custom callback when user is unauthenticated (prevents automatic redirect) */
  onUnauthenticated?: () => void;
}

type SessionContextValue<R extends boolean = false> = R extends true
  ?
      | { update: UpdateSession; data: Session; status: "authenticated" }
      | { update: UpdateSession; data: null; status: "loading" }
  :
      | { update: UpdateSession; data: Session; status: "authenticated" }
      | {
          update: UpdateSession;
          data: null;
          status: "unauthenticated" | "loading";
        };

type UpdateSession = (data?: any) => Promise<Session | null>;

Usage Examples:

// Basic usage
import { useSession } from "next-auth/react";

export default function Component() {
  const { data: session, status } = useSession();

  if (status === "loading") return <p>Loading...</p>;

  if (status === "unauthenticated") return <p>Access Denied</p>;

  return (
    <>
      <h1>Protected Page</h1>
      <p>You can view this page because you are signed in.</p>
      <p>Welcome {session.user?.name}</p>
    </>
  );
}

// Required authentication with redirect
export default function ProtectedComponent() {
  const { data: session } = useSession({ required: true });

  // This will automatically redirect to sign-in if not authenticated
  return <p>Welcome {session?.user?.name}</p>;
}

// Custom unauthenticated handler
export default function ConditionalComponent() {
  const { data: session, status } = useSession({
    required: false,
    onUnauthenticated: () => {
      // Custom handling instead of redirect
      console.log("User not authenticated");
    },
  });

  return (
    <div>
      {session ? (
        <UserContent user={session.user} />
      ) : (
        <GuestContent />
      )}
    </div>
  );
}

Sign In Function

Client-side function to initiate authentication flow with support for multiple providers and custom options.

/**
 * Initiate sign-in flow or redirect to sign-in page
 * @param provider - Authentication provider ID or undefined for provider selection
 * @param options - Sign-in configuration options
 * @param authorizationParams - Additional OAuth authorization parameters
 * @returns Promise with sign-in result (for credentials/email providers)
 */
function signIn<P extends RedirectableProviderType | undefined = undefined>(
  provider?: LiteralUnion<
    P extends RedirectableProviderType
      ? P | BuiltInProviderType
      : BuiltInProviderType
  >,
  options?: SignInOptions,
  authorizationParams?: SignInAuthorizationParams
): Promise<
  P extends RedirectableProviderType ? SignInResponse | undefined : undefined
>;

interface SignInOptions {
  /** URL to redirect to after successful sign-in */
  callbackUrl?: string;
  /** Whether to redirect after sign-in (default: true) */
  redirect?: boolean;
  /** Additional form data for credentials provider */
  [key: string]: any;
}

interface SignInAuthorizationParams {
  /** Additional OAuth authorization parameters */
  [key: string]: string;
}

interface SignInResponse {
  /** Error message if sign-in failed */
  error: string | undefined;
  /** HTTP status code */
  status: number;
  /** Whether sign-in was successful */
  ok: boolean;
  /** URL user was redirected to (null if error) */
  url: string | null;
}

type RedirectableProviderType = "email" | "credentials";
type BuiltInProviderType = RedirectableProviderType | OAuthProviderType;

Usage Examples:

import { signIn } from "next-auth/react";

// Sign in with OAuth provider (redirects to provider)
function LoginButton() {
  return (
    <button onClick={() => signIn("google")}>
      Sign in with Google
    </button>
  );
}

// Sign in with custom callback URL
function CustomLoginButton() {
  return (
    <button 
      onClick={() => signIn("github", { 
        callbackUrl: "/dashboard" 
      })}
    >
      Sign in with GitHub
    </button>
  );
}

// Sign in with credentials (no redirect)
async function handleCredentialsLogin(email: string, password: string) {
  const result = await signIn("credentials", {
    email,
    password,
    redirect: false,
  });

  if (result?.error) {
    console.error("Sign in failed:", result.error);
  } else {
    console.log("Sign in successful");
  }
}

// Generic sign-in (shows provider selection page)
function SignInButton() {
  return (
    <button onClick={() => signIn()}>
      Sign in
    </button>
  );
}

Sign Out Function

Client-side function to sign out the current user with customizable redirect behavior.

/**
 * Sign out the current user
 * @param options - Sign-out configuration options
 * @returns Promise with sign-out result (if redirect is disabled)
 */
function signOut<R extends boolean = true>(
  options?: SignOutParams<R>
): Promise<R extends true ? undefined : SignOutResponse>;

interface SignOutParams<R extends boolean = true> {
  /** URL to redirect to after sign-out */
  callbackUrl?: string;
  /** Whether to redirect after sign-out (default: true) */
  redirect?: R;
}

interface SignOutResponse {
  /** URL user was redirected to */
  url: string;
}

Usage Examples:

import { signOut } from "next-auth/react";

// Basic sign out (redirects to home page)
function SignOutButton() {
  return (
    <button onClick={() => signOut()}>
      Sign out
    </button>
  );
}

// Sign out with custom redirect
function CustomSignOutButton() {
  return (
    <button onClick={() => signOut({ callbackUrl: "/goodbye" })}>
      Sign out
    </button>
  );
}

// Sign out without redirect
async function handleSignOut() {
  const data = await signOut({ redirect: false });
  console.log("Signed out, redirect URL:", data.url);
  // Handle custom post-signout logic
}

Get Session Function

Client-side function to manually fetch the current session (typically not needed when using useSession).

/**
 * Manually fetch session data on the client side
 * @param params - Request context and options
 * @returns Promise resolving to session object or null
 */
function getSession(params?: GetSessionParams): Promise<Session | null>;

interface GetSessionParams extends CtxOrReq {
  /** Event that triggered session fetch */
  event?: "storage" | "timer" | "hidden" | string;
  /** Whether to trigger session sync event */
  triggerEvent?: boolean;
  /** Whether to broadcast session change to other tabs */
  broadcast?: boolean;
}

interface CtxOrReq {
  /** Request object (for SSR contexts) */
  req?: Partial<IncomingMessage> & { body?: any };
  /** App context containing request object */
  ctx?: { req: Partial<IncomingMessage> & { body?: any } };
}

Usage Example:

import { getSession } from "next-auth/react";

// Manually refresh session
async function refreshSession() {
  const session = await getSession();
  console.log("Current session:", session);
}

// Get session in event handler
async function handleButtonClick() {
  const session = await getSession();
  if (session) {
    // Perform authenticated action
  }
}

Get CSRF Token

Function to retrieve the current CSRF token for custom form submissions.

/**
 * Get the current CSRF token for POST requests
 * @param params - Request context
 * @returns Promise resolving to CSRF token string
 */
function getCsrfToken(params?: CtxOrReq): Promise<string | undefined>;

Usage Example:

import { getCsrfToken } from "next-auth/react";

// Custom form with CSRF protection
export default function CustomForm() {
  const [csrfToken, setCsrfToken] = useState("");

  useEffect(() => {
    getCsrfToken().then(token => setCsrfToken(token || ""));
  }, []);

  return (
    <form method="post" action="/api/auth/callback/credentials">
      <input name="csrfToken" type="hidden" value={csrfToken} />
      <input name="email" type="email" required />
      <input name="password" type="password" required />
      <button type="submit">Sign in</button>
    </form>
  );
}

Get Providers

Function to retrieve the list of configured authentication providers.

/**
 * Get list of configured authentication providers
 * @returns Promise resolving to provider configuration object
 */
function getProviders(): Promise<
  Record<LiteralUnion<BuiltInProviderType>, ClientSafeProvider> | null
>;

interface ClientSafeProvider {
  /** Provider ID */
  id: string;
  /** Provider display name */
  name: string;
  /** Provider type */
  type: string;
  /** Sign-in URL */
  signinUrl: string;
  /** Callback URL */
  callbackUrl: string;
}

Usage Example:

import { getProviders, signIn } from "next-auth/react";

export default function SignIn() {
  const [providers, setProviders] = useState<Record<string, ClientSafeProvider> | null>(null);

  useEffect(() => {
    getProviders().then(setProviders);
  }, []);

  return (
    <div>
      {providers &&
        Object.values(providers).map((provider) => (
          <div key={provider.name}>
            <button onClick={() => signIn(provider.id)}>
              Sign in with {provider.name}
            </button>
          </div>
        ))}
    </div>
  );
}

Session Context

React context for accessing session data directly (typically used internally by useSession).

/**
 * React context for session data
 */
const SessionContext: React.Context<SessionContextValue | undefined>;

interface SessionContextValue<R extends boolean = false> {
  /** Session data (null if not authenticated) */
  data: Session | null;
  /** Session status */
  status: "loading" | "authenticated" | "unauthenticated";
  /** Function to update session data */
  update: UpdateSession;
}

Session State Management

Session Status States

type SessionStatus = "loading" | "authenticated" | "unauthenticated";

interface SessionState {
  /** Current session status */
  status: SessionStatus;
  /** Session data when authenticated */
  data: Session | null;
  /** Last sync timestamp */
  lastSync: number;
  /** Whether session is being fetched */
  loading: boolean;
}

Session Update Patterns

/**
 * Session update function signature
 */
type UpdateSession = (data?: any) => Promise<Session | null>;

interface SessionUpdateOptions {
  /** New session data to merge */
  data?: any;
  /** Whether to broadcast update to other tabs */
  broadcast?: boolean;
  /** Custom event type for update */
  event?: string;
}

Usage Examples:

// Update session with new data
const { data: session, update } = useSession();

async function updateProfile(newProfile: any) {
  // Update session with new profile data
  await update({
    ...session,
    user: {
      ...session?.user,
      ...newProfile,
    },
  });
}

// Trigger session refresh
async function refreshUserData() {
  await update(); // Refetch session from server
}

Types

React-Specific Types

interface SessionProviderProps {
  children: React.ReactNode;
  session?: Session | null;
  baseUrl?: string;
  basePath?: string;
  refetchInterval?: number;
  refetchOnWindowFocus?: boolean;
  refetchWhenOffline?: false;
}

interface UseSessionOptions<R extends boolean> {
  required?: R;
  onUnauthenticated?: () => void;
}

type LiteralUnion<T extends U, U = string> = T | (U & Record<never, never>);

type OAuthProviderType = 
  | "42-school" | "apple" | "atlassian" | "auth0" | "authentik" 
  | "azure-ad-b2c" | "azure-ad" | "battlenet" | "box" | "boxyhq-saml"
  | "cognito" | "coinbase" | "discord" | "dribbble" | "dropbox"
  | "duende-identity-server6" | "eveonline" | "facebook" | "faceit"
  | "foursquare" | "freshbooks" | "fusionauth" | "github" | "gitlab"
  | "google" | "hubspot" | "identity-server4" | "instagram" | "kakao"
  | "keycloak" | "line" | "linkedin" | "mailchimp" | "mailru" | "medium"
  | "netlify" | "notion" | "oauth" | "okta" | "onelogin" | "osso"
  | "patreon" | "pinterest" | "pipedrive" | "reddit" | "salesforce"
  | "slack" | "spotify" | "strava" | "todoist" | "trakt" | "twitch"
  | "twitter" | "united-effects" | "vk" | "wikimedia" | "wordpress"
  | "workos" | "yandex" | "zitadel" | "zoho" | "zoom";

docs

authentication-providers.md

core-authentication.md

database-integration.md

index.md

jwt-management.md

middleware-protection.md

react-integration.md

server-side-sessions.md

tile.json