Skillpedia
واجهات API والخوادم (backend)40k · #7467

upstash-redis

ما الذي تفعله

تتيح لك هذه المهارة استخدام قاعدة بيانات Redis عبر الإنترنت دون اتصالات معقدة. وهي مفيدة لتخزين المعلومات المؤقتة (التخزين المؤقت)، وإدارة جلسات المستخدمين، وتحديد عدد مرات تنفيذ شيء ما خلال فترة زمنية (تحديد المعدل).

متى تستخدمها

  • ✓عندما تحتاج إلى تخزين بيانات مؤقتًا للوصول السريع إليها.
  • ✓عندما تريد إدارة تسجيلات الدخول والمعلومات لكل مستخدم متصل.
  • ✓عندما تريد منع المستخدم من إساءة استخدام ميزة بتحديد عدد الطلبات.

رابط المهارة

https://github.com/github/awesome-copilot/blob/main/skills/upstash-redis/SKILL.md

انسخه والصقه في الذكاء الاصطناعي الذي تستخدمه (Claude أو ChatGPT أو Cursor) واطلب منه اتباع التعليمات.

طريقة الاستخدام

أسهل طريقة: انسخ الرسالة والصقها في الذكاء الاصطناعي الذي تستخدمه. سيقرأ المهارة وينفّذ تعليماتها.

رسالة جاهزة للصق

استخدم هذه المهارة لمساعدتي: https://github.com/github/awesome-copilot/blob/main/skills/upstash-redis/SKILL.md اقرأ ملف SKILL.md في هذا الرابط ونفّذ تعليماته لمهمتي.
تريد أن يجد الذكاء الاصطناعي مهارات مثل هذه بنفسه؟ثبّت خادم Skillpedia MCP المجاني: سطر واحد، ويبحث في 15,000+ مهارة قبل كل مهمة.ثبّته في دقيقة واحدة →

مثال على ما تطلبه من الذكاء الاصطناعي

“ضع حدًا للطلبات عند 10 في الدقيقة لصفحة تسجيل الدخول.”

5 مهارات جديدة كل أسبوع. قراءة في دقيقة واحدة.

كيف تعمل

تعمل المهارة بإرسال أوامر إلى Redis عبر طلبات الويب (HTTP). وتُضبط ببيانات الاعتماد التي تحصل عليها من خدمة Upstash Redis.

المحتوى التقني (ملف SKILL.md الأصلي)

النص الأصلي من المؤلف، مباشرة من GitHub.

Upstash Redis Skill

This skill covers the three things serverless apps most often need Redis for: caching, sessions, and rate limiting. The client talks to Redis over HTTP, so it works where a long-lived TCP connection does not (edge middleware, short lived functions). Follow the steps in order; each ends with a checkpoint.

Requirements and limitations

  • An Upstash Redis database (hosted service; usage-based pricing with a free tier). Credentials are a REST URL and token from the database page.
  • Environment variables UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN.
  • Every command is an HTTP request. Batch with pipeline() or MGET/MSET when you issue many commands per request; avoid KEYS * in production.
  • Values are serialized automatically (objects, arrays, numbers round-trip). Do not JSON.stringify before set or parseInt after get.

Step 1 — Install and create one client per module

npm install @upstash/redis @upstash/ratelimit
// lib/redis.ts
import { Redis } from "@upstash/redis";

// Reads UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN
export const redis = Redis.fromEnv();

Create the client at module scope, not inside the request handler, so ephemeral caches and pipelines can be reused across invocations.

Checkpoint: await redis.ping() returns "PONG".

Step 2 — Cache-aside with TTL

import { redis } from "@/lib/redis";

type User = { id: string; name: string; plan: "free" | "pro" };

export async function getUser(userId: string): Promise<User | null> {
  const key = `user:${userId}`;
  const cached = await redis.get<User>(key);
  if (cached) return cached;

  const user = await db.users.findById(userId); // your data source
  if (user) await redis.set(key, user, { ex: 3600 }); // 1 hour TTL
  return user;
}

export async function updateUser(userId: string, patch: Partial<User>) {
  const user = await db.users.update(userId, patch);
  await redis.set(`user:${userId}`, user, { ex: 3600 }); // write-through
  return user;
}

export async function deleteUser(userId: string) {
  await db.users.delete(userId);
  await redis.del(`user:${userId}`); // invalidate
}

Always set a TTL on cache entries; namespace keys (user:123, session:abc).

Checkpoint: second call to getUser returns without hitting the database and await redis.ttl("user:123") is positive.

Step 3 — Sessions with sliding expiration

import { redis } from "@/lib/redis";

const SESSION_TTL = 60 * 60 * 24; // 24 hours

export async function createSession(userId: string, data: Record<string, unknown>) {
  const sessionId = crypto.randomUUID();
  await redis.set(`session:${sessionId}`, { userId, ...data, createdAt: Date.now() }, { ex: SESSION_TTL });
  return sessionId;
}

export async function getSession<T = Record<string, unknown>>(sessionId: string) {
  const session = await redis.get<T>(`session:${sessionId}`);
  if (session) await redis.expire(`session:${sessionId}`, SESSION_TTL); // slide
  return session;
}

export async function destroySession(sessionId: string) {
  await redis.del(`session:${sessionId}`);
}

Store the session id in an HttpOnly; Secure; SameSite cookie; never put the Redis token in client code.

Checkpoint: getSession after createSession returns the object with userId; after destroySession it returns null.

Step 4 — Rate limiting a route handler

// app/api/search/route.ts (Next.js App Router; same pattern for any fetch handler)
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "10 s"), // 10 requests per 10 seconds
  prefix: "ratelimit:search", // isolate keys per limiter
});

export async function POST(request: Request) {
  const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "anonymous";
  const { success, limit, remaining, reset } = await ratelimit.limit(ip);

  if (!success) {
    return new Response("Too Many Requests", {
      status: 429,
      headers: {
        "X-RateLimit-Limit": String(limit),
        "X-RateLimit-Remaining": String(remaining),
        "Retry-After": String(Math.max(0, Math.ceil((reset - Date.now()) / 1000))),
      },
    });
  }

  // handle the request
  return Response.json({ ok: true });
}
  • Identifier: use the user id or API key when authenticated; fall back to IP.

…

الأسئلة الشائعة

هل أحتاج إلى تثبيت شيء؟

نعم، تحتاج إلى تثبيت المكتبتين `@upstash/redis` و`@upstash/ratelimit` باستخدام مدير حزم مثل npm.

ما هي متغيرات البيئة؟

هي متغيرات تخزن فيها المعلومات الحساسة، مثل كلمات المرور ومفاتيح الوصول، كرابط Upstash Redis والرمز، حتى لا تظهر في الكود.

هل أستطيع استخدامها في أي مكان؟

تعمل جيدًا في البيئات بدون خوادم وعلى الحافة (مثل Vercel وCloudflare Workers)، حيث قد تكون الاتصالات الدائمة مشكلة. ولا تناسب إذا كان لديك بالفعل اتصال TCP مستقر بـ Redis على خادم تقليدي.

التفاصيل

الوصف الأصلي من المؤلف

Use Redis over HTTP from serverless and edge runtimes with @upstash/redis, and add rate limiting with @upstash/ratelimit. Use when the user mentions Upstash Redis, needs Redis from a Next.js route handler or middleware, Vercel, Cloudflare Workers, Deno, or Bun without TCP connection pooling, or wants cache-aside with TTLs, a session store, counters, or a 429 rate limiter using fixed window, slidin

repo: github/awesome-copilot

الشعبية

نجوم GitHub
40k
الترتيب
#7467
الترخيص
MIT
آخر تحديث
15‏/10‏/2026

هل هذه المهارة مفيدة؟

0

سجّل الدخول للتصويت.

التعليقات

  • …

المزيد من المهارات من هذا المستودع

مهارات مشابهة