Protect Pages

Learn how to protect pages for authenticated users.

Configure your authentication middleware to automatically secure selected pages. The middleware validates every request and redirects unauthenticated traffic to your Login Endpoint.

Add Protected Pages to Auth Middleware

Configure your protected routes by updating the requireAuth options in src/wristband.ts:

// src/wristband.ts

// ...

export const requireMiddlewareAuth = wristbandAuth.createMiddlewareAuth({
  authStrategies: ['SESSION'],
  sessionConfig: {
    sessionOptions,
    sessionEndpoint: '/api/auth/session'
  },
  protectedPages: [
    '/',            // Protect home page
    '/dashboard',   // Protect dashboard page
    '/settings(.*)' // Protect all settings pages (e.g., /settings/profile, /settings/billing)
  ],
});

The authentication middleware intercepts requests to protected pages to validate the user's session state:

  • If the user has an authenticated session, the page loads normally.
  • If the user does not have an authenticated session, they're redirected to your application's Login Endpoint.

Manual Page Protection in SSR Pages (Optional)

When you need precise control or unique handling for specific routes, bypass the global middleware and check the user's session manually inside getServerSideProps.

Note: Middleware protection alone is typically sufficient for most use cases.

// src/pages/dashboard.tsx

import type { GetServerSideProps } from 'next';
import { getSession } from 'src/wristband';

export const getServerSideProps: GetServerSideProps = async (context) => {
  const session = await getSession(context.req, context.res);

  // Redirect if not authenticated
  if (!session.isAuthenticated) {
    return {
      redirect: { destination: '/api/auth/login', permanent: false },
    };
  }

  // Pass session data to your component
  return {
    props: { userId: session.userId, tenantId: session.tenantId },
  };
};

export default function Dashboard({ userId, tenantId }: { userId: string; tenantId: string }) {
  return (
    <div>
      <h1>Dashboard</h1>
      <p>User ID: USERID</p>
      <p>Tenant ID: {tenantId}</p>
    </div>
  );
}


What’s Next

Your pages are now protected at the server level. Next, let's protect your API routes so only authenticated requests can access them.

Did this page help you?