• Wrap your getServerSideProps with this method to make sure the user is authenticated before visiting the page.

    // pages/protected-page.js
    import { withPageAuthRequired } from '@auth0/nextjs-auth0';

    export default function ProtectedPage() {
    return <div>Protected content</div>;
    }

    export const getServerSideProps = withPageAuthRequired();

    If the user visits /protected-page without a valid session, it will redirect the user to the login page. Then they will be returned to /protected-page after login.

    Type Parameters

    • P extends {
          [key: string]: any;
      } = {
          [key: string]: any;
      }

    • Q extends ParsedUrlQuery<Q> = ParsedUrlQuery

    Parameters

    Returns PageRoute<P, Q>

  • Wrap your Server Component with this method to make sure the user is authenticated before visiting the page.

    // app/protected-page/page.js
    import { withPageAuthRequired } from '@auth0/nextjs-auth0';

    export default function withPageAuthRequired(ProtectedPage() {
    return <div>Protected content</div>;
    }, { returnTo: '/protected-page' });

    If the user visits /protected-page without a valid session, it will redirect the user to the login page.

    Note: Server Components are not aware of the req or the url of the page. So if you want the user to return to the page after login, you must specify the returnTo option.

    You can specify a function to returnTo that accepts the params (An object containing the dynamic route parameters) and searchParams (An object containing the search parameters of the current URL) argument from the page, to preserve dynamic routes and search params.

    // app/protected-page/[slug]/page.js
    import { withPageAuthRequired } from '@auth0/nextjs-auth0';

    export default function withPageAuthRequired(ProtectedPage() {
    return <div>Protected content</div>;
    }, {
    returnTo({ params }) {
    return `/protected-page/${params.slug}`
    }
    });

    Returns AppRouterPageRoute