Overview
Clerk provides:- Secure sign-in and sign-up functionality
- Session management
- User profile management
- Authentication middleware for protected routes
Prerequisites
Before setting up authentication, you need:- A Clerk account (sign up here)
- A Clerk application created in your dashboard
- Your Clerk publishable and secret keys
Installation
Clerk is already included in the project dependencies:package.json
Configuration
Add Clerk environment variables
Add the following variables to your
.env.local file:Get your keys from the Clerk Dashboard under API Keys.
Configure ClerkProvider
The
ClerkProvider is configured in the root layout (app/layout.tsx):app/layout.tsx
Protecting API routes
Use Clerk’sgetAuth helper to protect API endpoints and get the authenticated user:
app/api/generate/route.ts
Public vs protected routes
Public routes
These routes are accessible without authentication:/- Home page/terms- Terms of service/privacy- Privacy policy/support- Support page/api/health- Health check endpoint
Protected routes
All other routes require authentication, including:- Credit management endpoints
- README generation
- README history
- Payment verification
User identification
Clerk provides a uniqueuserId for each authenticated user. This ID is used throughout the application to:
- Associate credits with users in the database
- Store README generation history
- Process payments and verify transactions
Best practices
- Always validate authentication in API routes that handle sensitive operations
- Use
NEXT_PUBLIC_prefix only for keys that need to be accessed client-side - Set appropriate redirect URLs for your production environment
- Test authentication flows in both development and production environments
Troubleshooting
Authentication not working
- Verify your Clerk keys are correct in
.env.local - Ensure the
ClerkProviderwraps your entire application - Check that middleware is properly configured
- Restart your development server after adding environment variables
Redirect loops
- Verify your
afterSignInUrlandafterSignUpUrlare correctly set - Ensure public routes are properly defined in the middleware
- Check that the root route (
/) is marked as public
Next steps
- Configure environment variables for all services
- Set up local development environment
- Learn about deployment considerations