{"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.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install next-protected-auth"],"cli":null},"imports":["import { NextAuthProtectedLogin } from 'next-protected-auth';","import { useNextAuthProtectedHandler } from 'next-protected-auth';","import { useNextAuthProtected } from 'next-protected-auth';","import { NextAuthProtectedCallback } from 'next-protected-auth';"],"auth":{"required":false,"env_vars":[]},"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}