Options
All
  • Public
  • Public/Protected
  • All
Menu

Module helpers/with-page-auth-required

Index

Server Type aliases

GetServerSidePropsResultWithSession

GetServerSidePropsResultWithSession<P>: GetServerSidePropsResult<P & { user?: Claims | null }>

If you wrap your getServerSideProps with WithPageAuthRequired your props object will be augmented with the user property, which will be the user's Claims

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

export default function Profile({ user }) {
  return <div>Hello {user.name}</div>;
}

export const getServerSideProps = withPageAuthRequired();

Type parameters

  • P = any

PageRoute

PageRoute<P>: (cts: GetServerSidePropsContext) => Promise<GetServerSidePropsResultWithSession<P>>

A page route that has been augmented with WithPageAuthRequired

Type parameters

  • P

Type declaration

WithPageAuthRequired

WithPageAuthRequired: { <P>(opts?: WithPageAuthRequiredOptions<P>): PageRoute<P>; <P>(Component: ComponentType<P>, options?: WithPageAuthRequiredOptions): FC<P> }

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 declaration

WithPageAuthRequiredOptions

WithPageAuthRequiredOptions<P>: { getServerSideProps?: GetServerSideProps<P>; returnTo?: string }

If you have a custom returnTo url you should specify it in returnTo.

You can pass in your own getServerSideProps method, the props returned from this will be merged with the user props. You can also access the user session data by calling getSession inside of this method, eg:

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

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

export const getServerSideProps = withPageAuthRequired({
  returnTo: '/foo',
  async getServerSideProps(ctx) {
    // access the user session
    const session = getSession(ctx.req, ctx.res);
    return { props: { customProp: 'bar' } };
  }
});

Type parameters

  • P = any

Type declaration

  • Optional getServerSideProps?: GetServerSideProps<P>
  • Optional returnTo?: string