{"id":16861,"library":"next-protected-auth","title":"Next Protected Auth","description":"Next Protected Auth is a JavaScript/TypeScript library designed to simplify the implementation of protected routes and authentication flows within Next.js applications. It provides a set of React components and hooks that abstract common authentication logic for login, logout, and auth callbacks, aiming to reduce boilerplate in Next.js projects. The current stable version is 2.0.450, indicating active maintenance with frequent patch releases, aligning with updates in the Next.js ecosystem. While not a full-fledged authentication provider like Auth.js (formerly NextAuth.js), it focuses specifically on the client-side integration of existing authentication systems with Next.js's routing and middleware for securing routes and managing user sessions. It differentiates itself by providing granular, component-based control over authentication UI and logic hooks.","status":"active","version":"2.0.450","language":"javascript","source_language":"en","source_url":"https://github.com/qlaffont/next-protected-auth","tags":["javascript","typescript"],"install":[{"cmd":"npm install next-protected-auth","lang":"bash","label":"npm"},{"cmd":"yarn add next-protected-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add next-protected-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime dependency for Next.js application functionality and routing. Version updates are frequent.","package":"next"},{"reason":"Peer dependency for building user interfaces with React components and hooks.","package":"react"},{"reason":"Peer dependency for rendering React components to the DOM.","package":"react-dom"}],"imports":[{"note":"This library primarily targets ES Modules and TypeScript. CommonJS 'require' syntax is incorrect.","wrong":"const NextAuthProtectedLogin = require('next-protected-auth').NextAuthProtectedLogin;","symbol":"NextAuthProtectedLogin","correct":"import { NextAuthProtectedLogin } from 'next-protected-auth';"},{"note":"This is a named export; a default import will fail.","wrong":"import useNextAuthProtectedHandler from 'next-protected-auth';","symbol":"useNextAuthProtectedHandler","correct":"import { useNextAuthProtectedHandler } from 'next-protected-auth';"},{"note":"Returns the connection status and a setter for it, indicating if a user is authenticated.","symbol":"useNextAuthProtected","correct":"import { useNextAuthProtected } from 'next-protected-auth';"},{"note":"Component designed to handle the post-authentication callback from an OAuth provider.","symbol":"NextAuthProtectedCallback","correct":"import { NextAuthProtectedCallback } from 'next-protected-auth';"}],"quickstart":{"code":"import { useNextAuthProtectedHandler, NextAuthProtectedLogin } from 'next-protected-auth';\nimport { useRouter } from 'next/router';\nimport type { AppProps } from 'next/app';\nimport { useEffect } from 'react';\n\n// This setup is typically for Next.js Pages Router in pages/_app.tsx\n// For App Router, you'd integrate the handler within middleware or a root layout.\nexport default function MyApp({ Component, pageProps }: AppProps) {\n  const router = useRouter();\n\n  // Configure the authentication handler for route protection\n  const { isConnected, setIsConnected } = useNextAuthProtectedHandler({\n    publicURLs: ['/', '/about', '/auth/login', '/auth/callback'],\n    loginURL: '/auth/login',\n    authCallbackURL: '/auth/callback',\n    renewTokenFct: (oldAccessToken?: string) => {\n      // Implement your token renewal logic here, e.g., an API call to refresh tokens\n      console.log('Attempting to renew token:', oldAccessToken);\n      // In a real app, this would be an async operation returning a new token or throwing an error.\n      return 'new-mock-access-token'; // Return the new access token\n    },\n    verifyTokenFct: (accessToken?: string) => {\n      // Implement your token verification logic here, e.g., check JWT expiration locally or via an API\n      console.log('Verifying token:', accessToken);\n      // Return a string indicating validity ('valid', 'expired', etc.) or empty if invalid\n      return accessToken && accessToken !== 'expired-token' ? 'valid' : '';\n    },\n    allowNotFound: true, // Allows unauthenticated users to see 404 pages\n  });\n\n  useEffect(() => {\n    // Example: React to connection status for UI updates or additional redirects\n    if (isConnected) {\n      console.log('User is authenticated!');\n    } else {\n      console.log('User is not authenticated.');\n    }\n  }, [isConnected]);\n\n  // Render specific authentication components based on the current path\n  if (router.pathname === '/auth/login') {\n    return (\n      <NextAuthProtectedLogin\n        callback={() => {\n          console.log('Login initiated. Redirecting user to OAuth provider...');\n          // Example: window.location.href = process.env.NEXT_PUBLIC_OAUTH_LOGIN_URL ?? '';\n        }}\n        authCallbackURL=\"/auth/callback\"\n      />\n    );\n  }\n\n  // Render the main application component\n  return <Component {...pageProps} />;\n}","lang":"typescript","description":"This quickstart demonstrates how to integrate `next-protected-auth` into a Next.js Pages Router application (`_app.tsx`), using the `useNextAuthProtectedHandler` hook to manage global route protection, public URLs, and token validation logic. It also shows basic usage of the `NextAuthProtectedLogin` component for initiating an authentication flow."},"warnings":[{"fix":"Review the official `next-protected-auth` GitHub releases for a changelog or migration guide. Adapt your code to the new API if necessary, particularly regarding component props or hook signatures.","message":"Major version `2.x` likely introduced breaking changes compared to `1.x`. While specific changes are not detailed in the truncated README, developers upgrading from `1.x` should consult the GitHub repository's release notes or changelog for specific migration steps.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Regularly update your `next` dependency to the latest secure version. For self-hosted Next.js applications, specifically ensure patches for CVE-2025-29927 (affecting Next.js versions before 12.3.5, 13.5.9, 14.2.25, and 15.2.3) and CVE-2024-51479 (affecting Next.js versions >= 9.5.5, < 14.2.15) are applied.","message":"This library relies on Next.js middleware for route protection. Next.js has experienced several critical authorization bypass vulnerabilities (e.g., CVE-2025-29927, CVE-2024-51479) related to middleware. Ensure your Next.js installation is always updated to the latest patched version to mitigate these risks.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Stay informed about Next.js release notes and major version upgrade guides. Test your authentication flows thoroughly after any Next.js version upgrade and adapt your integration as needed.","message":"The functionality of `next-protected-auth` is tightly coupled with Next.js routing and server-side features. Updates to Next.js itself, especially those concerning middleware, App Router vs. Pages Router, or server-side data fetching, may require adjustments to your implementation using this library. Next.js 15, for example, introduced significant breaking changes in areas like async request APIs and caching, which could impact how authentication flows are managed.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure `useNextAuthProtectedHandler` is called correctly at the root of your application's client-side rendering tree. Carefully define all `publicURLs` that should be accessible without authentication, including your login, auth callback, and any other publicly accessible pages.","message":"The `useNextAuthProtectedHandler` hook is intended to be used in a top-level component (e.g., `_app.tsx` for Pages Router, or potentially a root layout for App Router) to manage global authentication state and redirects. Misplacing this hook or not providing adequate public URLs can lead to infinite redirect loops or unintended access restrictions, including making login pages inaccessible.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure that all calls to `useNextAuthProtectedHandler` and `useNextAuthProtected` are made strictly within the scope of a React functional component or a custom hook.","cause":"The `useNextAuthProtectedHandler` or `useNextAuthProtected` hooks are being called outside of a React functional component or a custom hook.","error":"Error: Invalid hook call. Hooks can only be called inside of the body of a function component."},{"fix":"Install the package using `npm install next-protected-auth` or `yarn add next-protected-auth`. Double-check the import statement for typos.","cause":"The `next-protected-auth` package has not been installed, or there's a typo in the import path.","error":"Module not found: Can't resolve 'next-protected-auth'"},{"fix":"Verify that you are using named imports for all exports from `next-protected-auth`, for example: `import { useNextAuthProtectedHandler } from 'next-protected-auth';` rather than `import useNextAuthProtectedHandler from 'next-protected-auth';`.","cause":"This usually indicates an incorrect import, specifically trying to use a named export as a default export, or a module resolution issue where the bundler cannot correctly identify the specific named export.","error":"TypeError: (0, next_protected_auth__WEBPACK_IMPORTED_MODULE_0__.useNextAuthProtectedHandler) is not a function"}],"ecosystem":"npm","meta_description":null}