jpskill.com
🛠️ 開発・MCP コミュニティ

api-database-vercel-kv

Vercel KVというサーバーレスなデータベースを使い、高速なデータ保存とJSON形式の自動変換、有効期限付きキャッシュ機能で、ウェブサイトのパフォーマンスを向上させるSkill。

📜 元の英語説明(参考)

Serverless Redis-compatible key-value store via Upstash REST API -- edge-compatible, automatic JSON serialization, TTL-based caching

🇯🇵 日本人クリエイター向け解説

一言でいうと

Vercel KVというサーバーレスなデータベースを使い、高速なデータ保存とJSON形式の自動変換、有効期限付きキャッシュ機能で、ウェブサイトのパフォーマンスを向上させるSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o api-database-vercel-kv.zip https://jpskill.com/download/10238.zip && unzip -o api-database-vercel-kv.zip && rm api-database-vercel-kv.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10238.zip -OutFile "$d\api-database-vercel-kv.zip"; Expand-Archive "$d\api-database-vercel-kv.zip" -DestinationPath $d -Force; ri "$d\api-database-vercel-kv.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して api-database-vercel-kv.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → api-database-vercel-kv フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Vercel KV / Upstash Redis のパターン

クイックガイド: サーバーレスでエッジ互換の Redis を REST API 経由で使用するには、@upstash/redis@vercel/kv の後継)を使用します。重要な注意点: REST は TCP Redis と比較して、1 回の呼び出しあたり約 5〜15ms のレイテンシを追加します。すべての値は JSON として自動的にシリアライズされます(オブジェクトは透過的にラウンドトリップしますが、Date オブジェクトは文字列になります)。pipeline/multi は単一の HTTP リクエストとして実行されますが、pipeline はアトミックではありません。自動接続には Redis.fromEnv() を使用します。常に TTL を設定してください。サーバーレス Redis はコマンドごとに課金されます。


<critical_requirements>

重要: この Skill を使用する前に

すべてのコードは CLAUDE.md のプロジェクト規約に従う必要があります (kebab-case、名前付きエクスポート、インポート順序、import type、名前付き定数)

(新しいプロジェクトには必ず @upstash/redis を使用してください。@vercel/kv は 2024 年 12 月に非推奨となり、すべてのストアが Upstash Redis に移行されました)

(キャッシュされたすべてのデータに TTL を設定する必要があります。サーバーレス Redis はコマンドごとに課金され、プランごとにストレージ制限があります)

(これは TCP Redis クライアントではなく、REST/HTTP クライアントであることを理解する必要があります。各コマンドは ~5〜15ms のオーバーヘッドを持つ HTTP リクエストであるため、可能な場合はパイプラインでバッチ処理してください)

</critical_requirements>


  • コアパターン -- クライアント設定、CRUD 操作、TTL、ハッシュ、パイプライン、トランザクション、レート制限、セッション

追加リソース:

  • reference.md -- コマンドクイックリファレンス、環境変数、プラン制限

自動検出: Vercel KV, @vercel/kv, @upstash/redis, Upstash Redis, KV_REST_API_URL, KV_REST_API_TOKEN, UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN, Redis.fromEnv, kv.set, kv.get, kv.hset, kv.hget, kv.incr, kv.expire, kv.del, createClient, automaticDeserialization, edge Redis, serverless Redis

使用する場面:

  • Vercel サーバーレス/エッジ関数での API レスポンスまたはデータベースクエリのキャッシュ
  • エッジでのレート制限(スライディングウィンドウカウンター)
  • サーバーレスアプリケーションのセッションストレージ
  • フィーチャーフラグ、A/B テストの割り当て、または短期間のカウンター
  • TCP 接続が利用できない Vercel 上の Redis のユースケース(エッジランタイム)

カバーする主なパターン:

  • クライアントの初期化 (Redis.fromEnv()new Redis())
  • 自動 JSON シリアライゼーションによる基本的な CRUD
  • TTL と有効期限戦略
  • 構造化データのためのハッシュ操作
  • パイプライン(バッチ HTTP)とトランザクション(アトミック MULTI/EXEC)
  • ソートされたセットによるレート制限
  • セッションストレージパターン

使用しない場面:

  • 高スループット、低レイテンシの Redis ワークロード(TCP で ioredis を使用 - REST はリクエストごとにオーバーヘッドを追加します)
  • Pub/Sub サブスクライバー(REST はリクエスト-レスポンスであり、永続的な接続ではありません)
  • Redis Streams コンシューマー(ioredis のような TCP クライアントが必要です)
  • 大量の値のストレージ(無料プランではレコードあたり >1 MB、コマンド数で課金)
  • プライマリデータベース(Redis はキャッシュ/一時的なストアであり、信頼できる情報源ではありません)

<philosophy>

哲学

Upstash Redis(旧 Vercel KV)は、TCP 接続が利用できない、または実用的でないエッジおよびサーバーレスランタイム向けに設計された サーバーレスの REST ベースの Redis です。主なトレードオフ: どこでも HTTP 互換性がありますが、リクエストごとのレイテンシオーバーヘッドが発生します。

コア原則:

  1. REST ファースト -- すべての Redis コマンドは HTTP リクエストです。これはどこでも(エッジ、サーバーレス、ブラウザ)動作しますが、1 回の呼び出しあたり約 5〜15ms を追加します。パイプラインでバッチ処理します。
  2. 自動シリアライゼーション -- オブジェクトは書き込み時に JSON シリアライズされ、読み取り時にデシリアライズされます。これは便利ですが、Date オブジェクト、MapSet、および関数が忠実に保持されないことを意味します。
  3. 設計上、一時的 -- すべてに TTL を設定します。サーバーレス Redis はコマンドごとに課金され、ストレージ上限があります。データベースではなく、キャッシュとして扱ってください。
  4. 接続管理不要 -- 接続プール、再接続ロジック、error イベントハンドラーはありません。各リクエストはステートレス HTTP です。

</philosophy>


<patterns>

コアパターン

良い例と悪い例を含む完全な実装: examples/core.md

パターン 1: クライアントの初期化

2 つのアプローチ: Redis.fromEnv() (Vercel で推奨 - UPSTASH_REDIS_REST_URLUPSTASH_REDIS_REST_TOKEN を自動的に読み取ります) または明示的な構成のための new Redis({ url, token })。クレデンシャルをハードコードしないでください。

import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
export { redis };

パターン 2: 自動 JSON シリアライゼーション

SDK は、書き込み時にオブジェクトを JSON に自動的にシリアライズし、読み取り時にデシリアライズします。JSON.stringify を手動で呼び出さないでください。二重シリアライゼーションが発生します。型付きの戻り値には get<T>() を、タイプセーフな書き込みには satisfies を使用します。Date オブジェクトはラウンドトリップ時に ISO 文字列になります。代わりにタイムスタンプを数値として保存してください。

await redis.set("user:123", data satisfies UserProfile, { ex: TTL_SECONDS });
const user = await redis.get<UserProfile>("user:123"); // UserProfile | null

パターン 3: TTL と有効期限

常に TTL を設定してください。サーバーレス Redis はコマンドごとに課金されます。set(){ ex: seconds } または { px: milliseconds } を使用します。分散ロックには { nx: true } を使用します ( "OK" または null を返します)。TTL のないキーは、ストレージの無制限な増加を引き起こします。

await redis.set("cache:key", data, { ex: CACHE_TTL_SECONDS });

パターン 4: ハッシュ操作

ハッシュを使用すると、オブジェクト全体をシリアライズせずに、フィールドの一部を読み書きできます。複数フィールドの書き込みには hset、読み取りには hget/hgetall、アトミックカウンターには hincrby を使用します。注: hset は TTL を直接受け入れません。別途 expire() を呼び出してください。hgetall は、キーが存在しない場合、null を返します({} ではありません)。


パターン 5: パイプラインとトランザクション

パイプライン (redis.pipeline()) は、コマンドを単一の HTTP リクエストにバッチ処理しますが、アトミックではありません。トランザクション (redis.multi()) は、アトミックな MULTI/EXEC を提供し、これも単一の HTTP リクエストとして実行されます。複数のコマンドをバッチ処理できる場合は、連続した呼び出しを避けてください。各呼び出しは個別の HTTP ラウンドトリップです。


const pipe = redis.pipeline();
pipe.set("k1", "v1", { ex: TTL });
pi
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Vercel KV / Upstash Redis Patterns

Quick Guide: Use @upstash/redis (the successor to @vercel/kv) for serverless, edge-compatible Redis via REST API. Key gotchas: REST adds ~5-15ms latency per call vs TCP Redis, all values are auto-serialized as JSON (objects round-trip transparently but Date objects become strings), pipeline/multi execute as single HTTP requests but pipeline is NOT atomic. Use Redis.fromEnv() for automatic connection. Always set TTLs -- serverless Redis is billed per command.


<critical_requirements>

CRITICAL: Before Using This Skill

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST use @upstash/redis for new projects -- @vercel/kv was deprecated in December 2024 and all stores were migrated to Upstash Redis)

(You MUST set TTLs on all cached data -- serverless Redis is billed per command and has storage limits per plan)

(You MUST understand that this is a REST/HTTP client, NOT a TCP Redis client -- each command is an HTTP request with ~5-15ms overhead, so batch with pipelines when possible)

</critical_requirements>


Examples

  • Core Patterns -- Client setup, CRUD operations, TTL, hashes, pipelines, transactions, rate limiting, sessions

Additional resources:

  • reference.md -- Command quick reference, environment variables, plan limits

Auto-detection: Vercel KV, @vercel/kv, @upstash/redis, Upstash Redis, KV_REST_API_URL, KV_REST_API_TOKEN, UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN, Redis.fromEnv, kv.set, kv.get, kv.hset, kv.hget, kv.incr, kv.expire, kv.del, createClient, automaticDeserialization, edge Redis, serverless Redis

When to use:

  • Caching API responses or database queries in Vercel serverless/edge functions
  • Rate limiting at the edge (sliding window counters)
  • Session storage for serverless applications
  • Feature flags, A/B test assignments, or short-lived counters
  • Any Redis use case on Vercel where TCP connections are unavailable (edge runtime)

Key patterns covered:

  • Client initialization (Redis.fromEnv(), new Redis())
  • Basic CRUD with automatic JSON serialization
  • TTL and expiration strategies
  • Hash operations for structured data
  • Pipelines (batched HTTP) and transactions (atomic MULTI/EXEC)
  • Rate limiting with sorted sets
  • Session storage patterns

When NOT to use:

  • High-throughput, low-latency Redis workloads (use ioredis with TCP -- REST adds per-request overhead)
  • Pub/Sub subscribers (REST is request-response, not persistent connections)
  • Redis Streams consumers (requires TCP client like ioredis)
  • Large value storage (>1 MB per record on free tier, billed by command count)
  • Primary database (Redis is a cache/ephemeral store, not a source of truth)

<philosophy>

Philosophy

Upstash Redis (formerly Vercel KV) is a serverless, REST-based Redis designed for edge and serverless runtimes where TCP connections are unavailable or impractical. The core trade-off: HTTP compatibility everywhere, at the cost of per-request latency overhead.

Core principles:

  1. REST-first -- Every Redis command is an HTTP request. This works everywhere (edge, serverless, browsers) but adds ~5-15ms per call. Batch with pipelines.
  2. Auto-serialization -- Objects are JSON-serialized on write and deserialized on read. This is convenient but means Date objects, Map, Set, and functions are not preserved faithfully.
  3. Ephemeral by design -- Set TTLs on everything. Serverless Redis is billed per command and has storage caps. Treat it as a cache, not a database.
  4. Zero connection management -- No connection pools, no reconnection logic, no error event handlers. Each request is stateless HTTP.

</philosophy>


<patterns>

Core Patterns

Full implementations with good/bad pairs: examples/core.md

Pattern 1: Client Initialization

Two approaches: Redis.fromEnv() (preferred on Vercel -- reads UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN automatically) or new Redis({ url, token }) for explicit configuration. Never hardcode credentials.

import { Redis } from "@upstash/redis";
const redis = Redis.fromEnv();
export { redis };

Pattern 2: Automatic JSON Serialization

The SDK auto-serializes objects to JSON on write and deserializes on read. Never call JSON.stringify manually -- it causes double-serialization. Use get<T>() for typed returns, satisfies for type-safe writes. Date objects become ISO strings on round-trip -- store timestamps as numbers instead.

await redis.set("user:123", data satisfies UserProfile, { ex: TTL_SECONDS });
const user = await redis.get<UserProfile>("user:123"); // UserProfile | null

Pattern 3: TTL and Expiration

Always set TTLs -- serverless Redis is billed per command. Use { ex: seconds } or { px: milliseconds } on set(). Use { nx: true } for distributed locks (returns "OK" or null). Keys without TTLs cause unbounded storage growth.

await redis.set("cache:key", data, { ex: CACHE_TTL_SECONDS });

Pattern 4: Hash Operations

Hashes enable partial field reads/writes without serializing entire objects. Use hset for multi-field writes, hget/hgetall for reads, hincrby for atomic counters. Note: hset does not accept TTL directly -- call expire() separately. hgetall returns null for missing keys (not {}).


Pattern 5: Pipelines and Transactions

Pipelines (redis.pipeline()) batch commands into a single HTTP request but are NOT atomic. Transactions (redis.multi()) provide atomic MULTI/EXEC, also as a single HTTP request. Avoid sequential calls when multiple commands can be batched -- each call is a separate HTTP round-trip.

const pipe = redis.pipeline();
pipe.set("k1", "v1", { ex: TTL });
pipe.incr("counter");
const results = await pipe.exec<[string, number]>();

Important: Upstash REST transactions do NOT support WATCH for optimistic locking.


Pattern 6: Rate Limiting (Sliding Window)

Sliding window via sorted set scores -- zadd with timestamp as score, zremrangebyscore to prune expired entries, zcard to count, all batched in a pipeline. For production rate limiting, consider @upstash/ratelimit which provides built-in algorithms.


Pattern 7: Cache-Aside Helper

Generic cacheAside<T>(key, fetcher, ttl) pattern: check cache first, fetch on miss, fire-and-forget cache write to avoid blocking responses on cache failures.

</patterns>


<decision_framework>

Decision Framework

Upstash Redis vs ioredis/node-redis?

Which Redis client should I use?
+-- Running in Vercel Edge Runtime? -> @upstash/redis (only option -- no TCP)
+-- Running in Vercel Serverless Functions? -> @upstash/redis (simpler) or ioredis (if you need TCP features)
+-- Need Pub/Sub subscribers? -> ioredis (REST cannot maintain subscriptions)
+-- Need Redis Streams consumers? -> ioredis (requires persistent TCP connection)
+-- Need lowest possible latency (<1ms)? -> ioredis with TCP (REST adds HTTP overhead)
+-- Simple caching/sessions/counters? -> @upstash/redis (zero connection management)

Pipeline vs Transaction vs Sequential?

How should I batch commands?
+-- Need atomicity (all-or-nothing)? -> redis.multi() (transaction)
+-- Just reducing HTTP round-trips? -> redis.pipeline() (non-atomic batch)
+-- Single independent command? -> Direct call (redis.set, redis.get, etc.)

</decision_framework>


<red_flags>

RED FLAGS

High Priority Issues:

  • Using @vercel/kv in new projects -- deprecated December 2024, use @upstash/redis instead
  • Missing TTLs on cached keys -- causes unbounded storage growth and unexpected billing
  • Manual JSON.stringify/JSON.parse with Upstash Redis -- causes double-serialization because the SDK auto-serializes all values
  • Assuming pipeline commands are atomic -- pipelines batch for HTTP efficiency but do NOT guarantee atomicity (use multi() for atomic execution)

Medium Priority Issues:

  • Making sequential Redis calls where a pipeline would work -- each call is a separate HTTP round-trip (~5-15ms each)
  • Storing values >1 MB -- REST requests have size limits per plan (100 MB max on free/pay-as-you-go, but large values degrade performance)
  • Using Upstash Redis as a primary database -- it's a cache/ephemeral store, always have a source of truth elsewhere

Common Mistakes:

  • Expecting hgetall to return an empty object {} for missing keys -- Upstash returns null (unlike ioredis which returns {})
  • Forgetting that get() returns null (not undefined) for missing keys
  • Passing Date objects and expecting them to survive round-trip -- they serialize to ISO strings and come back as strings, not Date instances

Gotchas & Edge Cases:

  • automaticDeserialization: false breaks many TypeScript types -- only disable if you need raw string responses and are prepared to handle typing manually
  • set with ex option resets TTL on overwrite (standard Redis behavior) -- if you set a key that already has a TTL, the new ex value replaces it
  • REST latency is per-request, not per-command -- a pipeline with 10 commands has the same HTTP overhead as a single command (one round-trip)
  • Free tier is limited to 500K commands/month and 256 MB storage -- monitor usage in production
  • nx (set-if-not-exists) returns null on failure, "OK" on success -- check the return value explicitly

</red_flags>


<critical_reminders>

CRITICAL REMINDERS

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST use @upstash/redis for new projects -- @vercel/kv was deprecated in December 2024 and all stores were migrated to Upstash Redis)

(You MUST set TTLs on all cached data -- serverless Redis is billed per command and has storage limits per plan)

(You MUST understand that this is a REST/HTTP client, NOT a TCP Redis client -- each command is an HTTP request with ~5-15ms overhead, so batch with pipelines when possible)

Failure to follow these rules will cause deprecated package usage, unbounded storage costs, and unnecessary latency in serverless functions.

</critical_reminders>