Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

vercel-kv

БесплатноЗапускает вложенные скриптыНе проверен

Integrate Redis-compatible Vercel KV for caching, session management, and rate limiting in Next.js applications. Powered by Upstash with strong consistency…

ovachieverот ovachiever★ 56 звёзд на GitHub4 установки в других каталогах

Об этом скилле

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 URL
  • KV_REST_API_TOKEN - Auth token
  • KV_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}:profile instead 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

  1. Go to your Vercel project
  2. Storage → Create Database → KV
  3. Name your database
  4. 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
  • null is 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
Полный SKILL.md на GitHub

Установить vercel-kv в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.claude-plugin/plugin.jsonREADME.mdassets/example-template.txtreferences/example-reference.mdscripts/example-script.shtemplates/package.jsontemplates/session-management.tstemplates/simple-rate-limiting.ts

FAQ

Что делает скилл vercel-kv?

Integrate Redis-compatible Vercel KV for caching, session management, and rate limiting in Next.js applications. Powered by Upstash with strong consistency and TTL support. Use when implementing cache strategies, storing temporary data with expiration, building rate limiters, or troubleshooting missing environment variables, serialization errors, or rate limit issues.

Как установить скилл vercel-kv?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл vercel-kv запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить vercel-kv с