Protect Pages

Learn how to protect your pages so only authenticated users can access them.

In this section, you'll configure your authentication middleware to automatically protect specific pages in your application. The middleware validates authentication on every request and redirects unauthenticated users to your Login Endpoint.

Add Protected Pages to Auth Middleware

Update your requireAuth configuration in src/wristband.ts to specify which pages require authentication:

// 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)
  ],
});

When a user tries to access a page protected by the auth middleware, it will validate the user's session:

  • 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)

If you need more granular control or special handling of the authentication flow for specific pages, you can manually check the session in getServerSideProps instead of relying solely on middleware.

ℹ️

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.