Automated summary
This skill documents a database-backed rate limiting pattern built on a `usage_tracking` table to cap per-user consumption of Next.js API endpoints identified anonymously.
Strengths
- Provides complete, copy-ready TypeScript for anonymous identification (SHA-256 hash of IP + User-Agent), quota check, counter increment, and the 429 response
- Explains the 24-hour reset logic and the boundary-condition pitfalls to test
- Gives a clear procedure for adding a new counter via a new column or table
- Includes explicit guardrails: never expose identifiers, log counts rather than full hashes
Limitations
- Tightly coupled to one project: `app/api/generate-image/route.ts`, an existing Drizzle schema, and the `usage_tracking` table
- Does not address concurrency (read-then-write races, locking) or sliding-window limits
- IP + User-Agent identification is spoofable and unreliable behind shared proxies or clients that rotate headers
Use it when adding or tuning a usage quota (images, generations, requests) on a Next.js endpoint that already relies on Drizzle and a tracking table.
Skip it if the project does not use this Drizzle/Next.js stack, or if you need a distributed high-throughput limiter (Redis, sliding window) instead of a database counter.
Security analysis
SafeThe skill contains only TypeScript/ORM example code for implementing database-backed rate limiting. It performs no shell execution, network calls, file deletion, or secret handling. Hashing IP + User-Agent with SHA-256 is a privacy-minded design choice rather than an exfiltration risk; there is no obfuscation or attempt to disable safety controls.
No concerns found
How this analysis is madeExamples
Limit roasts to 5 per day per user using the existing usage_tracking table pattern.Add API request throttling to my generate-image route so each anonymous user gets 2 premium images per 24 hours, returning 429 when exceeded.Review my rate limit reset logic in usage_tracking and make sure the 24-hour boundary and counter increment are handled correctly.name: rate-limit-setup description: Implement rate limiting for API endpoints. Use when user mentions "rate limit", "quota", "usage tracking", "throttle", or "limit requests".
Rate Limiting Implementation
This project uses database-backed rate limiting via the usage_tracking table.
Current Implementation
Located in app/api/generate-image/route.ts:
- Limit: 2 premium images per user per 24 hours
- Identification: SHA-256 hash of IP + User-Agent (anonymous)
- Reset: Automatic after 24 hours
Instructions
- Create user identifier (anonymous hash):
const getUserIdentifier = async (req: NextRequest): Promise<string> => {
const ip = req.headers.get('x-forwarded-for')?.split(',')[0]
|| req.headers.get('x-real-ip')
|| 'unknown';
const userAgent = req.headers.get('user-agent') || 'unknown';
const encoder = new TextEncoder();
const data = encoder.encode(ip + userAgent);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
};
- Check and update usage:
import { db, usageTracking } from '@/db';
import { eq } from 'drizzle-orm';
const checkUsage = async (identifier: string, limit: number) => {
const existing = await db
.select()
.from(usageTracking)
.where(eq(usageTracking.userIdentifier, identifier))
.limit(1);
let usage = existing[0] || null;
const now = new Date();
const resetNeeded = !usage ||
now.getTime() - new Date(usage.lastResetAt!).getTime() > 24 * 60 * 60 * 1000;
if (!usage) {
const [inserted] = await db
.insert(usageTracking)
.values({ userIdentifier: identifier, premiumImagesCount: 0, lastResetAt: now })
.returning();
usage = inserted;
} else if (resetNeeded) {
const [updated] = await db
.update(usageTracking)
.set({ premiumImagesCount: 0, lastResetAt: now, updatedAt: now })
.where(eq(usageTracking.userIdentifier, identifier))
.returning();
usage = updated;
}
const withinLimit = (usage?.premiumImagesCount || 0) < limit;
return { withinLimit, usage };
};
- Increment counter after successful action:
await db
.update(usageTracking)
.set({
premiumImagesCount: (usage?.premiumImagesCount || 0) + 1,
updatedAt: new Date(),
})
.where(eq(usageTracking.userIdentifier, userIdentifier));
- Return appropriate response when limited:
if (!withinLimit) {
return NextResponse.json(
{ error: 'Rate limit exceeded. Try again in 24 hours.' },
{ status: 429, headers: corsHeaders }
);
}
For New Rate-Limited Features
If tracking a different resource, add a new column to usage_tracking or create a new table:
// In db/schema.ts
featureCount: integer('feature_count').default(0),
Examples
- "Limit roasts to 5 per day" → Add
roastCountcolumn, apply pattern above - "Add API request throttling" → Create new tracking table for general requests
Guardrails
- Never expose user identifiers in responses
- Log usage counts, not full hashes
- Use 429 status code for rate limit responses
- Include reset time info in rate limit responses when possible
- Test reset logic carefully (24-hour boundary)
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/rate-limiting-implementation-mma3jsh0' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/rate-limiting-implementation-mma3jsh0/download' --output '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md.part' && mv '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md.part' '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md' && test -s '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/rate-limit-setup' && cp -R '.skill-downloads/rate-limiting-implementation-mma3jsh0' '.claude/skills/rate-limit-setup'Cursor
test -f '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md' && test -s '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/rate-limit-setup' && cp -R '.skill-downloads/rate-limiting-implementation-mma3jsh0' '.cursor/skills/rate-limit-setup'Codex
test -f '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md' && test -s '.skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/rate-limit-setup' && cp -R '.skill-downloads/rate-limiting-implementation-mma3jsh0' '.agents/skills/rate-limit-setup'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/rate-limiting-implementation-mma3jsh0'openskills read 'rate-limiting-implementation-mma3jsh0'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/rate-limiting-implementation-mma3jsh0/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
DeFi AMM Security
Security
Security checklist for Solidity AMM contracts, liquidity pools, and swap flows. Covers reentrancy, donation attacks, oracle manipulation, slippage, and integer math.
Semgrep Rule Creator
Security
Creates custom Semgrep rules for detecting security vulnerabilities, bug patterns, and code patterns. Includes test-first methodology, taint mode support, and validation steps. Helps when building targeted static analysis detections.
Dev Toolbar Review Guide
Security
Safety rules for the dev toolbar, PostHog client, and feature flags. Use when reviewing changes to dev-tools and related files, covering environment guards, override cookies, and SSE stream safety.