Skip to content

Instantly share code, notes, and snippets.

@salala01
Created June 26, 2025 08:21
Show Gist options
  • Select an option

  • Save salala01/284e341afbef388758a3fc50eb360bf2 to your computer and use it in GitHub Desktop.

Select an option

Save salala01/284e341afbef388758a3fc50eb360bf2 to your computer and use it in GitHub Desktop.
Sample of ClaudeCode rate limit acquisition
import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import os from 'os'
interface ClaudeRecord {
timestamp: string
isApiErrorMessage?: boolean
message?: {
content?: Array<{
type: string
text: string
}>
}
}
interface RateLimitInfo {
record: ClaudeRecord
filePath: string
projectDir: string
}
export async function GET() {
try {
const homeDir = os.homedir()
const claudeProjectsDir = path.join(homeDir, '.claude', 'projects')
// Check if .claude/projects directory exists
if (!fs.existsSync(claudeProjectsDir)) {
return NextResponse.json({
status: 'no_claude_data',
message: 'Claude projects directory not found'
})
}
// Get list of project directories
const projectDirs = fs.readdirSync(claudeProjectsDir, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name)
if (projectDirs.length === 0) {
return NextResponse.json({
status: 'no_projects',
message: 'No Claude projects found'
})
}
const allRateLimitErrors: RateLimitInfo[] = []
// Collect rate limit errors from all files in all projects
for (const projectDir of projectDirs) {
const projectPath = path.join(claudeProjectsDir, projectDir)
try {
const files = fs.readdirSync(projectPath)
.filter(file => file.endsWith('.jsonl'))
// Process each JSONL file
for (const file of files) {
const filePath = path.join(projectPath, file)
try {
const content = fs.readFileSync(filePath, 'utf-8')
const lines = content.trim().split('\n')
// Check each line
for (const line of lines) {
if (!line.trim()) continue
try {
const record: ClaudeRecord = JSON.parse(line)
// Check if isApiErrorMessage is true and contains "Claude AI usage limit reached"
if (record.isApiErrorMessage && record.message?.content) {
const hasUsageLimitError = record.message.content.some(
(content) =>
content.type === 'text' &&
content.text.includes('Claude AI usage limit reached')
)
if (hasUsageLimitError) {
allRateLimitErrors.push({
record,
filePath,
projectDir
})
}
}
} catch (parseError) {
// Ignore JSON parse errors
continue
}
}
} catch (fileError) {
// Ignore file read errors
continue
}
}
} catch (dirError) {
// Ignore directory read errors
continue
}
}
// If no rate limit errors found
if (allRateLimitErrors.length === 0) {
return NextResponse.json({
status: 'ok',
message: 'No rate limit detected',
debugInfo: {
checkedProjects: projectDirs.length,
totalErrors: 0
}
})
}
// Get the latest rate limit error by timestamp
allRateLimitErrors.sort((a, b) =>
new Date(b.record.timestamp).getTime() - new Date(a.record.timestamp).getTime()
)
const latestError = allRateLimitErrors[0]
const errorText = latestError.record.message?.content?.find(
c => c.type === 'text' && c.text.includes('Claude AI usage limit reached')
)?.text || ''
const timestampMatch = errorText.match(/\|(\d+)/)
const resetTimestamp = timestampMatch ? parseInt(timestampMatch[1]) : null
const currentTime = Math.floor(Date.now() / 1000)
// Check if rate limit is still active
const isCurrentlyLimited = resetTimestamp ? currentTime < resetTimestamp : false
return NextResponse.json({
status: isCurrentlyLimited ? 'rate_limited' : 'rate_limit_expired',
message: isCurrentlyLimited
? 'Claude AI usage limit is currently active'
: 'Claude AI usage limit has expired',
timestamp: latestError.record.timestamp,
resetTimestamp: resetTimestamp,
resetTime: resetTimestamp ? new Date(resetTimestamp * 1000).toISOString() : null,
currentTime: new Date().toISOString(),
debugInfo: {
checkedProjects: projectDirs.length,
totalErrors: allRateLimitErrors.length,
latestErrorFrom: latestError.projectDir,
isCurrentlyLimited
}
})
} catch (error) {
console.error('Rate limit check error:', error)
return NextResponse.json({
status: 'error',
message: 'Failed to check rate limit status',
error: error instanceof Error ? error.message : 'Unknown error'
}, { status: 500 })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment