Protected Routes
Protected Routes and API Authentication in ShadcnKit
Understanding how ShadcnKit secures pages and API routes using Logto
ShadcnKit integrates Logto for authentication, providing a secure way to protect both pages and API routes. This system ensures that only authenticated users can access certain parts of your application and make specific API calls.
Protected Pages
How It Works
- Layout-based Protection: The
app/[locale]/dashboard/layout.tsx
file acts as a gatekeeper for all dashboard routes. - Authentication Check: It uses
getLogtoContext
to 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.ts
file provides utility functions for API authentication. - User Verification: The
requireAuth
function 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 the requireAuth
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.ts
to add additional checks or user data retrieval. - Adjust the redirect behavior in
app/[locale]/dashboard/layout.tsx
for unauthenticated users. - Implement role-based access control by extending the
requireAuth
function.
By leveraging ShadcnKit’s authentication system, you can ensure that your application’s sensitive areas and API endpoints are securely protected, providing a safe and personalized experience for your users.