Skip to main content
GitRead uses Clerk for secure user authentication and session management. This guide covers the authentication setup and configuration.

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
{
  "dependencies": {
    "@clerk/nextjs": "^5.0.0-beta.46"
  }
}

Configuration

1

Add Clerk environment variables

Add the following variables to your .env.local file:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_clerk_publishable_key
CLERK_SECRET_KEY=your_clerk_secret_key
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=/
Get your keys from the Clerk Dashboard under API Keys.
2

Configure ClerkProvider

The ClerkProvider is configured in the root layout (app/layout.tsx):
app/layout.tsx
import { ClerkProvider } from '@clerk/nextjs'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <ClerkProvider 
      afterSignInUrl="/"
      afterSignUpUrl="/"
    >
      <html lang="en" suppressHydrationWarning>
        <body className="bg-[#FBF9F5] dark:bg-gray-900">
          {children}
        </body>
      </html>
    </ClerkProvider>
  )
}
3

Set up authentication middleware

The middleware handles protected routes and custom redirects (middleware.ts:1):
middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'

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

export default clerkMiddleware(async (auth, req) => {
  // If it's a public route, allow access
  if (isPublicRoute(req)) {
    return NextResponse.next();
  }
  
  // For protected routes, authentication is required
})

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon.ico).*)',
    '/(api|trpc)(.*)'
  ],
}

Protecting API routes

Use Clerk’s getAuth helper to protect API endpoints and get the authenticated user:
app/api/generate/route.ts
import { getAuth } from '@clerk/nextjs/server'
import { NextRequest } from 'next/server'

export async function POST(req: NextRequest) {
  // Get authentication and require it
  const { userId } = getAuth(req)
  
  if (!userId) {
    return NextResponse.json({ 
      error: "Authentication required. Please sign in to generate README files."
    }, { status: 401 })
  }
  
  // Process authenticated request...
}

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 unique userId 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
const { userId } = getAuth(req)

// Use userId to query user-specific data
const { data } = await supabaseAdmin
  .from('user_credits')
  .select('credits')
  .eq('user_id', userId)
  .single()

Best practices

Never expose your CLERK_SECRET_KEY in client-side code. Only use it in server-side API routes and middleware.
  • 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

  1. Verify your Clerk keys are correct in .env.local
  2. Ensure the ClerkProvider wraps your entire application
  3. Check that middleware is properly configured
  4. Restart your development server after adding environment variables

Redirect loops

  1. Verify your afterSignInUrl and afterSignUpUrl are correctly set
  2. Ensure public routes are properly defined in the middleware
  3. Check that the root route (/) is marked as public

Next steps

Build docs developers (and LLMs) love