vercel-kv
БесплатноБез исполняемых скриптовНе проверенVercel KV, the Redis-compatible key-value store powered by Upstash, in Next.js and other Vercel applications. Covers @vercel/kv setup and environment…
Об этом скилле
Vercel KV (Redis-Compatible Storage)
Status: Production Ready
Last Updated: 2025-10-29
Dependencies: None
Latest Versions: @vercel/[email protected]
Quick Start (3 Minutes)
1. Create Vercel KV Database
# In your Vercel project dashboard
# Storage → Create Database → KV
# Pull environment variables locally
vercel env pull .env.local
This automatically creates:
KV_REST_API_URL- Your KV database URLKV_REST_API_TOKEN- Auth tokenKV_REST_API_READ_ONLY_TOKEN- Read-only token (optional)
2. Install Package
npm install @vercel/kv
3. Use in Your App
Next.js Server Action:
'use server';
import { kv } from '@vercel/kv';
export async function incrementViews(slug: string) {
const views = await kv.incr(`views:${slug}`);
return views;
}
Edge API Route:
import { kv } from '@vercel/kv';
export const runtime = 'edge';
export async function GET(request: Request) {
const value = await kv.get('mykey');
return Response.json({ value });
}
CRITICAL:
- Always set TTL for temporary data:
await kv.setex('key', 3600, value) - Use namespacing for keys:
user:${id}:profileinstead of just${id} - JSON values must be serializable (no functions, circular refs)
The 5-Step Setup Process
Step 1: Create KV Database
Option A: Vercel Dashboard
- Go to your Vercel project
- Storage → Create Database → KV
- Name your database
- Copy the environment variables
Option B: Vercel CLI
vercel env pull .env.local
This creates:
# .env.local (automatically created)
KV_REST_API_URL="https://xyz.kv.vercel-storage.com"
KV_REST_API_TOKEN="your-token-here"
KV_REST_API_READ_ONLY_TOKEN="your-readonly-token"
Key Points:
- One KV database per project recommended
- Free tier: 30,000 commands/month, 256MB storage
- Environment variables are automatically set for Vercel deployments
Step 2: Install and Configure
npm install @vercel/kv
For local development, create .env.local:
# .env.local
KV_REST_API_URL="https://your-db.kv.vercel-storage.com"
KV_REST_API_TOKEN="your-token"
For production, environment variables are automatically available.
Cloudflare Workers (using Vercel KV):
# wrangler.toml
[vars]
KV_REST_API_URL = "https://your-db.kv.vercel-storage.com"
secrets
KV_REST_API_TOKEN = "your-token"
Step 3: Basic Operations
Set/Get:
import { kv } from '@vercel/kv';
// Set a value
await kv.set('user:123', { name: 'Alice', email: '[email protected]' });
// Get a value
const user = await kv.get('user:123');
// Returns: { name: 'Alice', email: '[email protected]' }
// Set with TTL (expires in 1 hour)
await kv.setex('session:abc', 3600, { userId: 123 });
// Check if key exists
const exists = await kv.exists('user:123'); // Returns 1 if exists, 0 if not
// Delete a key
await kv.del('user:123');
Atomic Operations:
// Increment counter
const views = await kv.incr('views:post:123');
// Decrement counter
const stock = await kv.decr('inventory:item:456');
// Increment by amount
await kv.incrby('score:user:789', 10);
// Set if not exists (returns 1 if set, 0 if key already exists)
const wasSet = await kv.setnx('lock:process', 'running');
Multiple Operations:
// Get multiple keys
const values = await kv.mget('user:1', 'user:2', 'user:3');
// Returns: [{ name: '...' }, { name: '...' }, null]
// Set multiple keys
await kv.mset({
'user:1': { name: 'Alice' },
'user:2': { name: 'Bob' }
});
// Delete multiple keys
await kv.del('key1', 'key2', 'key3');
Key Points:
- Values are automatically JSON-serialized
nullis returned for non-existent keys- All operations are atomic
- TTL is in seconds
Step 4: Advanced Patterns
Caching Pattern:
import { kv } from '@vercel/kv';
async function getPost(slug: string) {
// Try cache first
const cached = await kv.get(`post:${slug}`);
if (cached) return cached;
// Fetch from database
const post = await db.select().from(posts).where(eq(posts.slug, slug));
// Cache for 1 hour
await kv.setex(`post:${slug}`, 3600, post);
return post;
}
Rate Limiting:
import { kv } from '@vercel/kv';
async function checkRateLimit(ip: string): Promise<boolean> {
const key = `ratelimit:${ip}`;
const limit = 10; // 10 requests
const window = 60; // per 60 seconds
const current = await kv.incr(key);
if (current === 1) {
// First request, set TTL
await kv.expire(key, window);
}
return current <= limit;
}
// Usage in API route
export async function POST(request: Request) {
const ip = request.headers.get('x-forwarded-for') || 'unknown';
if (!await checkRateLimit(ip)) {
return new Response('Rate limit exceeded', { status: 429 });
}
// Process request...
}
Session Management:
import { kv
Установить vercel-kv в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл vercel-kv?
Vercel KV, the Redis-compatible key-value store powered by Upstash, in Next.js and other Vercel applications. Covers @vercel/kv setup and environment variables (KV_REST_API_URL, KV_REST_API_TOKEN), key and JSON value operations, TTL and expiration, caching patterns for pages, APIs, and data, session and auth token storage, rate limiting, TypeScript usage from the edge runtime, serverless functions, and Server Actions, plus migrating from Cloudflare KV. Use when adding Vercel KV to an app, building a cache or rate limiter, storing sessions or temporary data with a TTL, choosing strongly consistent Redis-compatible storage over eventually consistent alternatives, or debugging KV_REST_API_URL not set, rate limit exceeded, or JSON serialization errors.
Как установить скилл vercel-kv?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл vercel-kv запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic