Guarding Pages

Learn how to guard pages in your Next.js Supabase application

As a server-side rendered application, Next.js Supabase will always render the page on the server before sending it to the client.

We assume you are in the context of a specific organization, as it is the primary use case for the Starter Kit.

We can use the function loadAppData to get data required to load the main layout of the app located at app/dashboard/[organization].

NB: you can call loadAppData multiple times because it uses caching.

In the following example, we are loading the user role within the organization that is currently selected.

import { redirect } from "next/navigation"; import loadAppData from '~/lib/server/loaders/load-app-data'; import MembershipRole from '~/lib/organizations/types/membership-role'; async function OnlyOwnersPage() { const data = await loadAppData(); const userRole = data.role; // if the user is not an owner, redirect them to the home page if (userRole !== MembershipRole.Owner) { redirect('/'); } // render the page }

As you can see above:

  1. We are loading the data required to render the page
  2. We are checking the user role within the organization
  3. If the user is not an owner, we redirect them to the home page (but feel free to change this)

Guarding Application Pages with Organization Subscriptions

In this example, we want to make sure the Organization is subscribed to a plan before allowing the user to access the page.

To do so, we check the subscription property of the Organization object and redirect the user to the dashboard if the subscription is active or trialing.

import { redirect } from "next/navigation"; import loadAppData from '~/lib/server/loaders/load-app-data'; async function OnlySubscribersPage() { const data = await loadAppData(); const status = data.organization.subscription?.data?.status; // if the subscription is not active, redirect the user to the dashboard if (!isSubscriptionActive(status)) { redirect('/'); } // render the page } function isSubscriptionActive(status: string | undefined) { return ['trialing', 'active'].includes(status); }

Subscribe to our Newsletter
Get the latest updates about React, Remix, Next.js, Firebase, Supabase and Tailwind CSS