Protect Pages and Server Components
Secure your pages and Server Components to restrict access to authenticated users.
In this section, you'll configure authentication middleware to lock down specific pages automatically. The middleware intercepts every request to validate the user's session, instantly redirecting unauthenticated users to the login page before any page content renders.
Add Protected Pages to Auth Middleware
While the authentication middleware automatically protects page-level Server Components (page.tsx files), it does not extend directly to sub-components or underlying layers. Specifically, the middleware leaves the following items unprotected:
- Nested Server Components within these pages (covered separately below)
- Server Actions (covered separately later in this guide)
Modify your requireAuth array in src/wristband.ts to specify which page routes require a valid session:
// src/wristband.ts
import { NextRequest } from 'next/server';
import { createWristbandAuth, getSessionFromRequest, SessionOptions } from '@wristband/nextjs-auth';
export const wristbandAuth = createWristbandAuth({
clientId: '<WRISTBAND_CLIENT_ID>',
clientSecret: '<WRISTBAND_CLIENT_SECRET>',
wristbandApplicationVanityDomain: '<WRISTBAND_APPLICATION_VANITY_DOMAIN>',
});
const sessionOptions: SessionOptions = {
secrets: '<your-generated-secret>'
};
export function getRequestSession(request: NextRequest) {
return getSessionFromRequest(request, sessionOptions);
}
// NEW: Add Protected page-level Server Components to the auth middleware.
export const requireAuth = 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 navigates to a route secured by the authentication middleware, the system evaluates their session through the following lifecycle:
- 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 Server Components (Optional)
For more granular control or custom page logic, you can manually verify sessions directly inside your Server Components instead of relying exclusively on middleware.
Note: Middleware protection alone is typically sufficient for most use cases.
Create Server Component Session Helper Function
First, add a getServerComponentSession() helper function to src/wristband.ts to grant your Server Components read-only access to session data.
Why Read-Only?Server Components run during the RSC payload generation phase, meaning they cannot alter response headers or cookies. Consequently, this helper provides read-only session data for access control and data fetching.
If you need to mutate a session (e.g., updating user data or logging out), implement a Server Action or an API route instead.
// src/wristband.ts
import { NextRequest } from 'next/server';
import {
createWristbandAuth,
getReadOnlySessionFromCookies,
getSessionFromRequest,
NextJsCookieStore,
SessionOptions,
} from '@wristband/nextjs-auth';
export const wristbandAuth = createWristbandAuth({
clientId: '<WRISTBAND_CLIENT_ID>',
clientSecret: '<WRISTBAND_CLIENT_SECRET>',
wristbandApplicationVanityDomain: '<WRISTBAND_APPLICATION_VANITY_DOMAIN>',
});
const sessionOptions: SessionOptions = {
secrets: '<your-generated-secret>'
};
export function getRequestSession(request: NextRequest) {
return getSessionFromRequest(request, sessionOptions);
}
export const requireAuth = wristbandAuth.createMiddlewareAuth({
authStrategies: ['SESSION'],
sessionConfig: {
sessionOptions,
sessionEndpoint: '/api/auth/session'
},
protectedPages: ['/', '/dashboard', '/settings(.*)'],
});
// NEW: Helper function that can be used to retrieve a read-only
// instance of the session within Server Components.
export function getServerComponentSession(cookieStore: NextJsCookieStore) {
return getReadOnlySessionFromCookies(cookieStore, sessionOptions);
}Page-level Server Component Protection
You can manually evaluate the session inside your page.tsx file and use Next.js's native redirect() function to send unauthenticated users to your login route.
// src/app/analytics/page.tsx
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { getServerComponentSession } from 'src/wristband';
export default async function AnalyticsPage() {
const cookieStore = await cookies();
const session = await getServerComponentSession(cookieStore);
// Redirect if not authenticated
if (!session.isAuthenticated) {
redirect('/api/auth/login');
}
// Render page with session data
return (
<div>
<h1>Analytics</h1>
<p>User ID: {session.userId}</p>
<p>Tenant ID: {session.tenantId}</p>
</div>
);
}Nested Server Component Protection
Note that nested Server Components within your page layout tree cannot initiate a redirect. The Next.js redirect() function only operates inside top-level page components (page.tsx), Server Actions, and API Route Handlers. For nested sub-components, you must rely on conditional rendering instead.
// src/app/dashboard/UserProfile.tsx
import { cookies } from 'next/headers';
import { getServerComponentSession } from 'src/wristband';
export default async function UserProfile() {
const cookieStore = await cookies();
const session = await getServerComponentSession(cookieStore);
if (!session.isAuthenticated) {
return <div>Please log in to view your profile.</div>;
}
// Render page with session data
return (
<div>
<h2>User Profile</h2>
<p>Email: {session.email}</p>
<p>Tenant: {session.tenantId}</p>
</div>
);
}Updated 14 days ago
What’s Next
Next, let's learn how we can enforce authentication on Server Actions.