🍪 Note: Our web-capstone-docs subdomain is a cookie-free zone.
Additional Libraries
Protect Entire App

Protect Entire App with Authentication

If the nature of your application, such as a messenger app, necessitates that all interactions occur post-login, you might consider implementing a global authentication requirement. A practical approach to achieve this is by requiring authentication across the entire app rather than on a page-by-page basis. This can be efficiently managed within the _app.js file, where you can set up a universal authentication check for all users accessing any part of the application.

export default function App({ Component, pageProps: { session, ...pageProps } }) {
  return (
    <SessionProvider session={session}>
        <Auth>
            <GlobalStyle />
            <Component {...pageProps} />
        </Auth>
    </SessionProvider>
  );
}
 
function Auth({ children }) {
  const { status } = useSession({ required: true });
 
  if (status === "loading") {
    return <div>Is loading</div>;
  }
  return children;
}

You cannot utilize the useSession hook in the <App> component because it exists outside the <SessionProvider>. However, you can create an <Auth> component that enforces authentication and only renders its children if the user is authenticated. This component should be nested within the <SessionProvider> to ensure proper context for session management.

When using the useSession hook with the configuration { required: true }, it ensures that the status remains either loading or authenticated. If these conditions are not met, NextAuth will automatically redirect the user to the login page.