Page Guards

MakerKit provides various utilities that allow you to restrict access to certain pages or API according to factors such as: sign-in state, role, membership plan, etc.

Protecting Next.js Pages

To protect against access to certain pages, we can use the function withAppProps. This function is a server-side props handler which will take care of checking the following conditions:

  • if the user is signed in - otherwise will be redirected back to the sign in page (this is customizable)
  • if the user is onboarded - otherwise will be redirected back to the onboarding
  • if the page they are trying to access requires a certain membership plan

Assuming you want to protect the Dashboard page, it will be as easy as:

import { withAppProps } from '~/lib/props/with-app-props';

export async function getServerSideProps(
  ctx: GetServerSidePropsContext
) {
  return await withAppProps(ctx);
}

It's likely that you will want to add additional logic, or additional props to be sent to the page. In this case, you can partially evaluate withAppProps and extend the props with other information:

import { withAppProps } from '~/lib/props/with-app-props';

export async function getServerSideProps(
  ctx: GetServerSidePropsContext
) {
  const { props: appProps } =
    await withAppProps(ctx);

  const data = await getDataFromDb();

  return {
    props: {
      ...appProps,
      data,
    }
  };
}

This handler takes the following parameters:

const DEFAULT_OPTIONS = {
  redirectPath: configuration.paths.signIn,
  locale: 'en',
  localeNamespaces: <string[]>[],
  requirePlans: <string[]>[],
}
  • redirectPath: by default, we redirect the user to the signIn page when they're not authenticated
  • redirectPath: by default, we use the en locale
  • localeNamespaces: additional namespaces you want to add to the route
  • requirePlans: a list of Stripe price IDs that you ma want to require to access this page. If you require more complex logic, it's best to handle it separately