Profiles·Public

next-auth

semver^4.22.0postconditions13functions8last verified2026-04-04coverage score95%

Postconditions — what we check

  • encode · encode-no-try-catch
    warning
    Whensecret parameter is undefined, null, or empty string; or EncryptJWT fails
    ThrowsTypeError from @panva/hkdf when secret is missing; Error from jose during encryption failure
    Required handlingCaller MUST wrap encode() in try/catch when called outside of NextAuth's own jwt.encode callback. Common error: NEXTAUTH_SECRET not set → TypeError from hkdf. Handle gracefully: log the configuration error and fail the request with 500. Note: encode() inside NextAuth's jwt.encode option is protected by the framework.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[1]
  • decode · decode-no-try-catch
    warning
    WhenToken encrypted with different secret (key rotation), malformed token, or missing secret
    ThrowsJWEDecryptionFailed (wrong secret), JWEInvalid/JWTInvalid (malformed), TypeError (missing secret)
    Required handlingCaller MUST wrap decode() in try/catch when calling directly. Common scenarios: 1. Secret rotation: old tokens throw JWEDecryptionFailed → return null/401, force re-auth 2. Malformed/tampered token: JWEInvalid → return 401, do not expose error details 3. Missing NEXTAUTH_SECRET: TypeError → configuration error, fail fast with clear message Note: getToken() from next-auth/jwt already wraps decode() in try/catch internally. This postcondition applies only to direct decode() calls.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[1]
  • getServerSession · getserversession-null-not-checked
    error
    WhenNo active session (user not logged in, expired token, or invalid cookie)
    Returnsnull
    Required handlingCaller MUST check the return value for null before accessing session properties. getServerSession() returns null when: no session cookie present, session expired, or token validation fails. Accessing .user or other properties on null causes TypeError. Pattern: const session = await getServerSession(authOptions); if (!session) return redirect('/login');
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • getServerSession · getserversession-authoptions-mismatch
    warning
    WhenauthOptions not passed or different from [...nextauth] route config
    Returnsnull (silently returns null when options mismatch)
    Required handlingCaller MUST pass the same authOptions object used in the [...nextauth] route handler. In App Router, getServerSession(authOptions) is required — omitting authOptions returns null silently. Common mistake: importing authOptions from wrong file or passing partial config. Always export authOptions from a single shared location.
    costhighin prodsilent failureusers seeauthentication failurevisibilitysilent
    Sources[2]
  • getToken · gettoken-null-not-checked
    error
    WhenNo valid JWT cookie present, token expired, or decode fails
    Returnsnull
    Required handlingCaller MUST check the return value for null before accessing token properties. getToken() returns null when: no session cookie, decode fails (wrong secret, malformed token), or cookie name doesn't match. Accessing properties on null causes TypeError. Pattern: const token = await getToken({ req }); if (!token) return res.status(401).json({ error: 'Unauthorized' });
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[3]
  • getToken · gettoken-missing-req
    warning
    Whenreq parameter is undefined or null
    ThrowsTypeError: Cannot read properties of undefined (reading 'headers')
    Required handlingCaller MUST pass a valid request object to getToken(). In API routes, pass { req }. In middleware, pass { req: request }. Missing req causes an immediate TypeError. This is a coding error, not a runtime condition — ensure req is always provided.
    costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4]
  • getToken · gettoken-missing-secret
    warning
    WhenNEXTAUTH_SECRET environment variable not set and no secret option provided
    ThrowsMissingSecret: Please define a `secret` in production by setting the NEXTAUTH_SECRET environment variable.
    Required handlingCaller MUST ensure NEXTAUTH_SECRET is set in the environment or pass secret option to getToken({ req, secret }). In development, NextAuth generates a random secret with a warning. In production, missing secret throws MissingSecret error. This is a deployment configuration issue — validate env vars at startup.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[1]
  • signIn · signin-error-not-checked
    error
    WhenAuthentication fails when called with redirect:false (wrong credentials, provider error)
    ReturnsSignInResponse with error field set (e.g., { error: 'CredentialsSignin', status: 401, ok: false, url: null })
    Required handlingWhen using signIn('credentials', { redirect: false }), caller MUST check the .error property of the returned object. signIn() does NOT throw on auth failure — it returns { error: 'CredentialsSignin', ok: false }. Common mistake: using try/catch instead of checking response.error. Pattern: const res = await signIn('credentials', { ...data, redirect: false }); if (res?.error) { showError(res.error); } else { router.push('/dashboard'); }
    costmediumin prodsilent failureusers seedegraded performancevisibilitysilent
    Sources[5]
  • signIn · signin-providers-fetch-failure
    warning
    WhenNetwork error when calling /api/auth/csrf or /api/auth/signin endpoint
    Returnsundefined (signIn returns undefined when the internal fetch fails)
    Required handlingCaller SHOULD handle the case where signIn() returns undefined, which happens when the internal fetch to the auth API fails (network error, server down). The internal fetchData utility catches fetch errors and returns null, which propagates as undefined from signIn(). Pattern: const res = await signIn(...); if (!res) { showNetworkError(); }
    costlowin prodsilent failureusers seedegraded performancevisibilitysilent
    Sources[5]
  • signOut · signout-network-error-not-handled
    warning
    WhenNetwork error when calling /api/auth/signout endpoint
    Returnsundefined (internal fetchData catches and returns null)
    Required handlingCaller SHOULD handle the case where signOut({ redirect: false }) returns undefined or the redirect fails due to network error. The internal fetchData utility catches fetch errors and returns null. If using redirect:false, check the return value before using .url property. Pattern: const res = await signOut({ redirect: false }); if (res?.url) { window.location.href = res.url; } else { showError('Sign out failed'); }
    costlowin prodsilent failureusers seedegraded performancevisibilitysilent
    Sources[6]
  • withAuth · withauth-no-secret
    warning
    WhenNEXTAUTH_SECRET not set and secret option not provided
    ReturnsRedirects to /api/auth/error page with console error logged
    Required handlingCaller MUST ensure NEXTAUTH_SECRET is set in the environment or pass secret option in middleware config. Without a secret, withAuth cannot decode the JWT token and redirects all users to the error page. This is a deployment configuration error. The middleware logs 'NO_SECRET' error to console. Validate env vars in CI/CD pipeline.
    costhighin proddegraded serviceusers seeservice unavailablevisibilityvisible
    Sources[7]
  • withAuth · withauth-authorized-callback-false
    warning
    Whenauthorized callback returns false (user authenticated but not authorized)
    ReturnsRedirects to sign-in page (not error page)
    Required handlingWhen using the authorized callback for role-based access, be aware that returning false redirects to the sign-in page, NOT an 'access denied' page. This can confuse authenticated users who lack permissions. To show a proper 403 page, handle authorization in the page component instead of the middleware authorized callback. Pattern: callbacks: { authorized: ({ token }) => token?.role === 'admin' }
    costlowin proddegraded serviceusers seedegraded performancevisibilityvisible
    Sources[7]
  • getSession · getsession-null-not-checked
    error
    WhenNo active session or network error fetching /api/auth/session
    Returnsnull
    Required handlingCaller MUST check the return value for null before accessing session properties. getSession() returns null when: user not authenticated, session expired, or network error fetching the session endpoint. The internal fetchData utility catches fetch errors and returns null. Accessing .user on null causes TypeError. Pattern: const session = await getSession(); if (!session) { redirectToLogin(); }
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[8]

Sources

Every postcondition cites at least one of these. Numbered to match the footnotes above.

  1. [1]next-auth.js.org/configuration/optionshttps://next-auth.js.org/configuration/options#secret
  2. [2]next-auth.js.org/configuration/nextjshttps://next-auth.js.org/configuration/nextjs#getserversession
  3. [3]next-auth.js.org/tutorials/securing-pages-and-api-routeshttps://next-auth.js.org/tutorials/securing-pages-and-api-routes#using-gettoken
  4. [4]next-auth.js.org/tutorials/securing-pages-and-api-routeshttps://next-auth.js.org/tutorials/securing-pages-and-api-routes
  5. [5]next-auth.js.org/getting-started/clienthttps://next-auth.js.org/getting-started/client#signin
  6. [6]next-auth.js.org/getting-started/clienthttps://next-auth.js.org/getting-started/client#signout
  7. [7]next-auth.js.org/configuration/nextjshttps://next-auth.js.org/configuration/nextjs#middleware
  8. [8]next-auth.js.org/getting-started/clienthttps://next-auth.js.org/getting-started/client#getsession
Need a different package?
Request a profile