Nextbase Docs
Guides

Creating Protected Page

Guide on how to create a protected page in a Next.js application such as in Nextbase.

Protected pages are internal web app pages such as dashboard, user settings etc. These pages usually require a condition to be met, and the common case is that the user must be authenticated.

All authenticated user pages should be children of this layout - src/app/(dynamic-pages)/(authenticated-pages)/layout.tsx. Because this layout handles checking if the user is authenticated or not. If the user is not authenticated, the user will be redirected to the login page.

src/app/(dynamic-pages)/(authenticated-pages)/layout.tsx
import { ReactNode } from 'react';
import { ClientLayout } from './ClientLayout';
import { redirect } from 'next/navigation';
import { createSupabaseUserServerComponentClient } from '@/supabase-clients/user/createSupabaseUserServerComponentClient';
 
export default async function Layout({ children }: { children: ReactNode }) {
  const { data, error } =
    await createSupabaseUserServerComponentClient().auth.getUser();
  if (error || !data.user) {
    return redirect('/login');
  }
 
  return <ClientLayout>{children}</ClientLayout>;
}

Middleware Protection

In addition to the layout-based protection, Nextbase uses middleware to enhance security and performance. The middleware runs before server components are rendered, allowing for early authorization checks.

src/middleware.ts
// In your middleware file
const unprotectedPagePrefixes = [
  '/',
  '/changelog',
  '/auth(/.)?',
  // ... other unprotected routes ...
];
function isUnprotectedPage(pathname: string) {
  // Check if the pathname matches any unprotected prefix
}
export async function middleware(req: NextRequest) {
  // Check user session and redirect if necessary
  // Handle onboarding and admin access
}

This middleware:

  1. Defines unprotected pages that don't require authentication
  2. Checks if the user is authenticated for protected routes
  3. Handles user onboarding and admin access
  4. Redirects unauthenticated users to the login page

By implementing both layout-based and middleware-based protection, you ensure robust security for your protected pages while maintaining good performance.

On this page