Next Protected Auth
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.
Common errors
-
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
cause The `useNextAuthProtectedHandler` or `useNextAuthProtected` hooks are being called outside of a React functional component or a custom hook.fixEnsure 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'
cause The `next-protected-auth` package has not been installed, or there's a typo in the import path.fixInstall 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
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.fixVerify 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';`.
Warnings
- breaking 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.
- breaking 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install next-protected-auth -
yarn add next-protected-auth -
pnpm add next-protected-auth
Imports
- NextAuthProtectedLogin
const NextAuthProtectedLogin = require('next-protected-auth').NextAuthProtectedLogin;import { NextAuthProtectedLogin } from 'next-protected-auth'; - useNextAuthProtectedHandler
import useNextAuthProtectedHandler from 'next-protected-auth';
import { useNextAuthProtectedHandler } from 'next-protected-auth'; - useNextAuthProtected
import { useNextAuthProtected } from 'next-protected-auth'; - NextAuthProtectedCallback
import { NextAuthProtectedCallback } from 'next-protected-auth';
Quickstart
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} />;
}