Protected Pages
How It Works
- Layout-based Protection: The
app/[locale]/dashboard/layout.tsxfile acts as a gatekeeper for all dashboard routes. - Authentication Check: It uses
getLogtoContextto verify if the user is authenticated. - Redirection: Unauthenticated users are automatically redirected to the home page.
Benefits
- Centralized authentication check for all dashboard routes
- Automatic redirection for unauthenticated users
- Localization support integrated into the authentication flow
Protected API Routes
How It Works
- Authentication Middleware: The
lib/auth.tsfile provides utility functions for API authentication. - User Verification: The
requireAuthfunction checks if a user is authenticated and retrieves their information. - Error Handling: Throws an error if the user is not authenticated, which can be caught and handled in API routes.
Usage in API Routes
API routes use therequireAuth function to ensure only authenticated users can access them:
Benefits
- Consistent authentication across all API routes
- Easy to implement and maintain
- Provides user information for authenticated requests
Key Features
- Seamless Integration: Logto authentication is seamlessly integrated into both page routing and API calls.
- Flexibility: Easy to adjust protection levels for different routes or API endpoints.
- User Context: Authenticated routes have access to user information for personalization.
- Localization Support: Authentication flows respect the application’s localization settings.
Customization
You can easily customize the authentication behavior:- Modify
lib/auth.tsto add additional checks or user data retrieval. - Adjust the redirect behavior in
app/[locale]/dashboard/layout.tsxfor unauthenticated users. - Implement role-based access control by extending the
requireAuthfunction.