Skip to main content
GitRead uses Clerk for authentication and session management. All API endpoints (except public routes) require a valid Clerk session to access.

Authentication flow

Clerk handles authentication automatically through middleware. When you make requests to protected API endpoints, Clerk validates your session and provides user information to the API.

How it works

  1. User signs in through the GitRead web interface
  2. Clerk creates a session and issues session tokens
  3. Session tokens are automatically included in API requests via cookies
  4. The API validates the session and extracts the userId
  5. The userId is used to access user-specific resources
You don’t need to manually include authentication headers when using the GitRead web application - Clerk handles this automatically.

Protected endpoints

The following endpoints require authentication:
  • POST /api/generate - Generate README files
  • GET /api/credits - View credit balance
  • POST /api/credits - Update credits
  • GET /api/readme-history - Retrieve generation history
  • POST /api/readme-history - Save README to history
  • POST /api/create-checkout-session - Create payment session
  • POST /api/verify-payment - Verify payments

Public endpoints

These routes are accessible without authentication:
  • / - Home page
  • /terms - Terms of service
  • /privacy - Privacy policy
  • /support - Support page
  • /api/health - Health check endpoint

Authentication in API routes

Each API route validates authentication using Clerk’s getAuth helper:
import { getAuth } from '@clerk/nextjs/server'
import { NextRequest } from 'next/server'

export async function POST(req: NextRequest) {
  const { userId } = getAuth(req)
  
  if (!userId) {
    return NextResponse.json(
      { error: 'Authentication required. Please sign in.' },
      { status: 401 }
    )
  }
  
  // Process authenticated request
}

Handling unauthorized requests

When you make a request without valid authentication, the API returns a 401 Unauthorized response:
{
  "error": "Authentication required. Please sign in."
}
The exact error message may vary by endpoint but will always include a 401 status code.

User identification

The userId extracted from Clerk sessions is used to:
  • Track user credit balance in the database
  • Associate generated READMEs with users
  • Verify payment ownership
  • Enforce per-user limits and quotas

Session management

Clerk sessions are managed through middleware configuration in middleware.ts:
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

const isPublicRoute = createRouteMatcher([
  '/', 
  '/terms', 
  '/privacy', 
  '/support',
  '/api/health'
])

export default clerkMiddleware(async (auth, req) => {
  if (isPublicRoute(req)) {
    return NextResponse.next()
  }
  // Protected routes require authentication
})

Environment variables

Clerk requires the following environment variables:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_SECRET_KEY=sk_test_...
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/
These variables configure Clerk’s behavior and define the authentication flow paths.

Best practices

Every protected endpoint should validate the userId before processing requests. Return a 401 error if authentication fails.
When accessing Supabase from API routes, use the service role key for operations that require elevated permissions:
const supabaseAdmin = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!
)
Never return sensitive authentication tokens or keys in API responses. Keep credentials server-side only.
When accessing user-specific resources, always verify that the authenticated user owns the resource:
.select('*')
.eq('user_id', userId)

Troubleshooting

”Unauthorized” errors

If you’re receiving 401 errors:
  1. Ensure you’re signed in to GitRead
  2. Check that your session hasn’t expired
  3. Verify Clerk environment variables are configured
  4. Clear cookies and sign in again

Session not persisting

If sessions aren’t persisting across requests:
  1. Check that cookies are enabled in your browser
  2. Verify the NEXT_PUBLIC_APP_URL matches your domain
  3. Ensure middleware is properly configured
For additional help with Clerk authentication, refer to the Clerk documentation.

Build docs developers (and LLMs) love