Registry / auth-security / next-protected-auth

next-protected-auth

JSON →
library2.0.450jsnpmunverified

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.

npm install next-protected-auth
INSTALL
IMPORT
SIG · NEXT-PROTECTED-AUT
N
next-protected-auth
auth-securityjavascriptv2.0.450
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

NextAuthProtectedLogin
import { NextAuthProtectedLogin } from 'next-protected-auth';
const NextAuthProtectedLogin = require('next-protected-auth').NextAuthProtectedLogin;
This library primarily targets ES Modules and TypeScript. CommonJS 'require' syntax is incorrect.
useNextAuthProtectedHandler
import { useNextAuthProtectedHandler } from 'next-protected-auth';
import useNextAuthProtectedHandler from 'next-protected-auth';
This is a named export; a default import will fail.
useNextAuthProtected
import { useNextAuthProtected } from 'next-protected-auth';
Returns the connection status and a setter for it, indicating if a user is authenticated.
NextAuthProtectedCallback
import { NextAuthProtectedCallback } from 'next-protected-auth';
Component designed to handle the post-authentication callback from an OAuth provider.

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.

import { useNextAuthProtectedHandler, NextAuthProtectedLogin } from 'next-protected-auth'; import { useRouter } from 'next/router'; import type { AppProps } from 'next/app'; import { useEffect } from 'react'; // This setup is typically for Next.js Pages Router in pages/_app.tsx // For App Router, you'd integrate the handler within middleware or a root layout. export default function MyApp({ Component, pageProps }: AppProps) { const router = useRouter(); // Configure the authentication handler for route protection const { isConnected, setIsConnected } = useNextAuthProtectedHandler({ publicURLs: ['/', '/about', '/auth/login', '/auth/callback'], loginURL: '/auth/login', authCallbackURL: '/auth/callback', renewTokenFct: (oldAccessToken?: string) => { // Implement your token renewal logic here, e.g., an API call to refresh tokens console.log('Attempting to renew token:', oldAccessToken); // In a real app, this would be an async operation returning a new token or throwing an error. return 'new-mock-access-token'; // Return the new access token }, verifyTokenFct: (accessToken?: string) => { // Implement your token verification logic here, e.g., check JWT expiration locally or via an API console.log('Verifying token:', accessToken); // Return a string indicating validity ('valid', 'expired', etc.) or empty if invalid return accessToken && accessToken !== 'expired-token' ? 'valid' : ''; }, allowNotFound: true, // Allows unauthenticated users to see 404 pages }); useEffect(() => { // Example: React to connection status for UI updates or additional redirects if (isConnected) { console.log('User is authenticated!'); } else { console.log('User is not authenticated.'); } }, [isConnected]); // Render specific authentication components based on the current path if (router.pathname === '/auth/login') { return ( <NextAuthProtectedLogin callback={() => { console.log('Login initiated. Redirecting user to OAuth provider...'); // Example: window.location.href = process.env.NEXT_PUBLIC_OAUTH_LOGIN_URL ?? ''; }} authCallbackURL="/auth/callback" /> ); } // Render the main application component return <Component {...pageProps} />; }
Debug
Known issues
breakingMajor 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.
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.
affects: >=2.0.0
breakingThis 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.
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.
affects: >=1.0.0
gotchaThe 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.
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.
affects: >=1.0.0
gotchaThe `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.
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.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
The `useNextAuthProtectedHandler` or `useNextAuthProtected` hooks are being called outside of a React functional component or a custom hook.
fix
Ensure that all calls to `useNextAuthProtectedHandler` and `useNextAuthProtected` are made strictly within the scope of a React functional component or a custom hook.
Module not found: Can't resolve 'next-protected-auth'
The `next-protected-auth` package has not been installed, or there's a typo in the import path.
fix
Install the package using `npm install next-protected-auth` or `yarn add next-protected-auth`. Double-check the import statement for typos.
TypeError: (0, next_protected_auth__WEBPACK_IMPORTED_MODULE_0__.useNextAuthProtectedHandler) is not a function
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.
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';`.
Upgrade
Version history
2.0.450latest on npm
Audit
Dependencies
nextrequiredRuntime dependency for Next.js application functionality and routing. Version updates are frequent.
reactrequiredPeer dependency for building user interfaces with React components and hooks.
react-domrequiredPeer dependency for rendering React components to the DOM.
Agent activity
9 hits · last 30 days
node
8
OpenAI (training)
1
Resources