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.
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.
This middleware:
- Defines unprotected pages that don't require authentication
- Checks if the user is authenticated for protected routes
- Handles user onboarding and admin access
- 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.