TITLE: Basic Usage of Upstash Redis Client DESCRIPTION: This TypeScript example illustrates how to initialize the Upstash Redis client with your REST URL and token, and then perform various common Redis operations including string manipulation (SET, GET), sorted sets (ZADD, ZRANGE), lists (LPUSH, LRANGE), hashes (HSET, HGET), and sets (SADD, SPOP). SOURCE: https://upstash.com/docs/redis/sdks/ts/getstarted.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // string await redis.set('key', 'value'); let data = await redis.get('key'); console.log(data) await redis.set('key2', 'value2', {ex: 1}); // sorted set await redis.zadd('scores', { score: 1, member: 'team1' }) data = await redis.zrange('scores', 0, 100 ) console.log(data) // list await redis.lpush('elements', 'magnesium') data = await redis.lrange('elements', 0, 100 ) console.log(data) // hash await redis.hset('people', {name: 'joe'}) data = await redis.hget('people', 'name' ) console.log(data) // sets await redis.sadd('animals', 'cat') data = await redis.spop('animals', 1) console.log(data) ``` ---------------------------------------- TITLE: Google Cloud Function: ioredis Redis Counter DESCRIPTION: This JavaScript code defines a Google Cloud Function (`helloGET`) that connects to an Upstash Redis instance using the `ioredis` client. It increments a 'counter' key in Redis with each invocation and returns the updated value as a page view count. Requires Redis connection details (endpoint, password, port). SOURCE: https://upstash.com/docs/redis/howto/getstartedgooglecloudfunctions.mdx LANGUAGE: javascript CODE: ``` var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.helloGET = async (req, res) => { let count = await client.incr("counter"); res.send("Page view:" + count); }; ``` ---------------------------------------- TITLE: Express Application with Redis Session Store DESCRIPTION: This JavaScript code defines an Express.js application that utilizes 'connect-redis' to persist session data in a Redis database. It initializes a Redis client, configures the session middleware with a Redis store, and sets up routes to demonstrate session-based view counting for different paths. SOURCE: https://upstash.com/docs/redis/tutorials/express_session.mdx LANGUAGE: javascript CODE: ``` var express = require("express"); var parseurl = require("parseurl"); var session = require("express-session"); const redis = require("redis"); var RedisStore = require("connect-redis")(session); var client = redis.createClient({ // REPLACE HERE }); var app = express(); app.use( session({ store: new RedisStore({ client: client }), secret: "forest squirrel", resave: false, saveUninitialized: true, }) ); app.use(function (req, res, next) { if (!req.session.views) { req.session.views = {}; } // get the url pathname var pathname = parseurl(req).pathname; // count the views req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; next(); }); app.get("/foo", function (req, res, next) { res.send("you viewed this page " + req.session.views["/foo"] + " times"); }); app.get("/bar", function (req, res, next) { res.send("you viewed this page " + req.session.views["/bar"] + " times"); }); app.listen(3000, function () { console.log("Example app listening on port 3000!"); }); ``` ---------------------------------------- TITLE: Python Examples for Redis SET Command DESCRIPTION: Illustrative Python code snippets demonstrating various ways to use the Redis `SET` command, including basic usage, conditional setting (NX/XX), setting expirations, and retrieving old values. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/set.mdx LANGUAGE: python CODE: ``` assert redis.set("key", "value") == True assert redis.get("key") == "value" ``` LANGUAGE: python CODE: ``` # Only set the key if it does not already exist. assert redis.set("key", "value", nx=True) == False # Only set the key if it already exists. assert redis.set("key", "value", xx=True) == True ``` LANGUAGE: python CODE: ``` # Set the key to expire in 10 seconds. assert redis.set("key", "value", ex=10) == True # Set the key to expire in 10000 milliseconds. assert redis.set("key", "value", px=10000) == True ``` LANGUAGE: python CODE: ``` # Get the old value stored at the key. assert redis.set("key", "new-value", get=True) == "old-value" ``` ---------------------------------------- TITLE: Initialize Upstash Redis in Node.js/Browser DESCRIPTION: Demonstrates how to initialize an Upstash Redis client in Node.js or browser environments. Configuration can be loaded from explicit URL/token environment variables or directly using `Redis.fromEnv()`. This method is suitable for platforms like Vercel, Netlify, and AWS Lambda. SOURCE: https://upstash.com/docs/redis/sdks/ts/deployment.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // or load directly from env const redis = Redis.fromEnv() ``` ---------------------------------------- TITLE: Fetch and Display Coin Data with Apollo GraphQL in Next.js DESCRIPTION: This Next.js component (`index.js`) defines a GraphQL query (`GET_COIN_LIST`) to retrieve a range of coin data from the 'coins' Redis list via the Upstash GraphQL API. It utilizes Apollo's `useQuery` hook to manage loading states and errors, parses the JSON string results, and dynamically renders a table displaying cryptocurrency names, prices, and images. A loading indicator is shown while data is being fetched. SOURCE: https://upstash.com/docs/redis/tutorials/coin_price_list.mdx LANGUAGE: javascript CODE: ``` import Head from "next/head"; import styles from "../styles/Home.module.css"; import { gql, useQuery } from "@apollo/client"; import React from "react"; const GET_COIN_LIST = gql` query { redisLRange(key: "coins", start: 0, stop: 6) } `; export default function Home() { let coins = []; const { loading, error, data } = useQuery(GET_COIN_LIST); if (!loading && !error) { for (let x of data.redisLRange) { let dd = JSON.parse(x); coins.push(dd); } } return (
Create Next App

Coin Price List

{!loading ? ( coins.map((item, ind) => ( )) ) : ( )}
{item.name} ${item.price}
); } ``` ---------------------------------------- TITLE: FastAPI Application with Redis Caching DESCRIPTION: Defines a FastAPI application that fetches weather data for a given city. It integrates with Upstash Redis to implement caching: it first checks if the data exists in the cache, otherwise it fetches from an external API and stores the result in Redis with a 10-minute expiration. SOURCE: https://upstash.com/docs/redis/tutorials/python_fastapi_caching.mdx LANGUAGE: python CODE: ``` from fastapi import FastAPI from upstash_redis import Redis import requests import os app = FastAPI() # Connect to Redis using environment variables redis = Redis.from_env() # Mock API endpoint for weather data WEATHER_API_URL = "https://api.weatherapi.com/v1/current.json" API_KEY = os.getenv("WEATHER_API_KEY") @app.get("/weather/{city}") def get_weather(city: str): cache_key = f"weather:{city}" # Check if the data exists in cache cached_data = redis.get(cache_key) if cached_data: return {"source": "cache", "data": cached_data} # Fetch data from external API response = requests.get(f"{WEATHER_API_URL}?key={API_KEY}&q={city}") weather_data = response.json() # Store the data in Redis cache with a 10-minute expiration redis.setex(cache_key, 600, weather_data) return {"source": "api", "data": weather_data} ``` ---------------------------------------- TITLE: Simple Node.js Express Application with Redis Counter DESCRIPTION: This JavaScript code defines a basic Express.js server that interacts with an Upstash Redis instance. It increments a 'counter' key in Redis on every GET request to the root path and displays the current visitor number. The application uses the `redis` client library and `util.promisify` for asynchronous Redis operations, connecting via the `REDIS_URL` environment variable. SOURCE: https://upstash.com/docs/redis/quickstarts/fly.mdx LANGUAGE: js CODE: ``` const express = require("express"); const redis = require("redis"); const { promisify } = require("util"); const app = express(); const client = redis.createClient(process.env.REDIS_URL); const getAsync = promisify(client.get).bind(client); const setAsync = promisify(client.set).bind(client); app.get("/", async (req, res) => { const value = await getAsync("counter"); await setAsync("counter", parseInt(value || 0) + 1); res.send(`Hello, visitor number ${value || 0}!`); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); ``` ---------------------------------------- TITLE: Increment Key Value in Redis (Python) DESCRIPTION: Demonstrates how to use the `INCR` command in Upstash Redis with a Python client. It shows setting an initial integer value for a key and then incrementing it, asserting the new value. This command handles non-existent keys by initializing them to 0 before incrementing. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/incr.mdx LANGUAGE: py CODE: ``` redis.set("key", 6) assert redis.incr("key") == 7 ``` ---------------------------------------- TITLE: Implement Caching in Laravel TodoController for CRUD Operations DESCRIPTION: Integrates caching into the `TodoController`'s CRUD methods using Laravel's `Cache::flexible` for retrieval and `Cache::forget` for invalidation. It defines cache keys and Time-To-Live (TTL) values, ensuring data freshness across read and write operations by invalidating relevant caches upon data modification. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: php CODE: ``` validate([ 'title' => 'required|string|max:255', ]); $todo = Todo::create($request->all()); // Invalidate the todos cache Cache::forget(self::CACHE_KEY); return response()->json($todo, Response::HTTP_CREATED); } /** * Display the specified resource. */ public function show(Todo $todo): Todo { return Cache::flexible( "todo.{$todo->id}", self::CACHE_TTL, function () use ($todo) { return $todo; } ); } /** * Update the specified resource in storage. */ public function update(Request $request, Todo $todo): JsonResponse { $request->validate([ 'title' => 'required|string|max:255', ]); $todo->update($request->all()); // Invalidate both the collection and individual todo cache Cache::forget(self::CACHE_KEY); Cache::forget("todo.{$todo->id}"); return response()->json($todo); } /** * Remove the specified resource from storage. */ public function destroy(Todo $todo): JsonResponse { $todo->delete(); // Invalidate both the collection and individual todo cache Cache::forget(self::CACHE_KEY); Cache::forget("todo.{$todo->id}"); return response()->json(null, Response::HTTP_NO_CONTENT); } } ``` ---------------------------------------- TITLE: Backend API: Create New Feature (Next.js, ioredis) DESCRIPTION: This Next.js API endpoint (`/api/create`) allows users to add new feature suggestions to the 'roadmap' Sorted Set in Upstash Redis. It uses the `ZADD` command with the 'NX' flag to prevent duplicate entries and includes validation for the feature title's presence and length. SOURCE: https://upstash.com/docs/redis/tutorials/roadmapvotingapp.mdx LANGUAGE: javascript CODE: ``` import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const title = body["title"]; if (!title) { redis.quit(); res.json({ error: "Feature can not be empty", }); } else if (title.length < 70) { await redis.zadd("roadmap", "NX", 1, title); redis.quit(); res.json({ body: "success", }); } else { redis.quit(); res.json({ error: "Max 70 characters please.", }); } }; ``` ---------------------------------------- TITLE: Python URL Shortener Application Core Logic DESCRIPTION: This comprehensive Python script defines the main functionalities of the URL shortener. It includes functions for generating unique short codes, storing original URLs in Redis with an optional expiration time, and retrieving the original URL based on a given short code. The script also demonstrates example usage within its `if __name__ == "__main__":` block. SOURCE: https://upstash.com/docs/redis/tutorials/python_url_shortener.mdx LANGUAGE: python CODE: ``` import string import random from upstash_redis import Redis from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Redis connection redis = Redis.from_env() # Characters to generate the short URL from CHARS = string.ascii_letters + string.digits BASE_URL = "https://short.url/" # Function to generate a random string for the short URL def generate_short_code(length=6): return ''.join(random.choices(CHARS, k=length)) # Function to shorten the URL with an expiration time def shorten_url(url, expiration=3600): # Generate a random short code short_code = generate_short_code() # Save the short code in Redis redis.set(short_code, url, ex=expiration) return BASE_URL + short_code # Function to get the original URL from the short URL def get_original_url(short_code): return redis.get(short_code) # Example usage if __name__ == "__main__": original_url = "https://example.com/my-very-long-url" # Shorten the URL short_url = shorten_url(original_url, expiration=600) print(f"Shortened URL: {short_url}") # Get the original URL original_url = get_original_url(short_url.split("/")[-1]) if original_url: print(f"Original URL: {original_url}") else: print("Short URL expired or not found") ``` ---------------------------------------- TITLE: Apply Different Ratelimits for Free and Paid Users DESCRIPTION: This snippet demonstrates how to configure and apply distinct ratelimits for different user groups, such as free and paid users. It utilizes separate `Ratelimit` instances, each with its own prefix and `slidingWindow` configuration, allowing for flexible rate management based on user attributes. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/features.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis"; import { Ratelimit } from "@upstash/ratelimit"; const redis = Redis.fromEnv(); const ratelimit = { free: new Ratelimit({ redis, analytics: true, prefix: "ratelimit:free", limiter: Ratelimit.slidingWindow(10, "10s"), }), paid: new Ratelimit({ redis, analytics: true, prefix: "ratelimit:paid", limiter: Ratelimit.slidingWindow(60, "10s"), }), }; await ratelimit.free.limit(ip); // or for a paid user you might have an email or userId available: await ratelimit.paid.limit(userId); ``` ---------------------------------------- TITLE: Client-side Feature Management (Next.js React Component) DESCRIPTION: This JavaScript code from the `Home` React component handles user interactions for a roadmap voting application. It includes functions to refresh feature data, vote on features, add new feature suggestions, and register email notifications, all by making `fetch` requests to various backend APIs. SOURCE: https://upstash.com/docs/redis/tutorials/roadmapvotingapp.mdx LANGUAGE: javascript CODE: ``` import Head from 'next/head' import { ToastContainer, toast } from 'react-toastify'; import * as React from "react"; class Home extends React.Component { ... refreshData() { fetch("api/list") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result.body }); this.inputNewFeature.current.value = ""; }, (error) => { this.setState({ isLoaded: true, error }); } ) } vote(event, title) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"title": title}) }; console.log(requestOptions); fetch('api/vote', requestOptions) .then(response => response.json()).then(data => { console.log(data) if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 3000}); } else { this.refreshData() } }) } handleNewFeature(event) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"title": this.inputNewFeature.current.value}) }; fetch('api/create', requestOptions) .then(response => response.json()).then(data => { if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 5000}); } else { toast.info("Your feature has been added to the list.", {hideProgressBar: true, autoClose: 3000}); this.refreshData() } }); event.preventDefault(); } handleNewEmail(event) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"email": this.inputEmail.current.value}) }; console.log(requestOptions); fetch('api/addemail', requestOptions) .then(response => response.json()).then(data => { if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 3000}); } else { toast.info("Your email has been added to the list.", {hideProgressBar: true, autoClose: 3000}); this.refreshData() } }); event.preventDefault(); } } export default Home; ``` ---------------------------------------- TITLE: Supabase Function Redis Counter Logic (TypeScript) DESCRIPTION: Implements the core logic for the Supabase function. It connects to Upstash Redis, increments a regional counter based on the 'DENO_REGION' environment variable (or 'localhost'), and returns the aggregated counter hash. SOURCE: https://upstash.com/docs/redis/quickstarts/supabase.mdx LANGUAGE: ts CODE: ``` import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; import { Redis } from "https://deno.land/x/upstash_redis@v1.19.3/mod.ts"; console.log(`Function "upstash-redis-counter" up and running!`); serve(async (_req) => { try { const redis = new Redis({ url: Deno.env.get("UPSTASH_REDIS_REST_URL")!, token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN")!, }); const deno_region = Deno.env.get("DENO_REGION"); if (deno_region) { // Increment region counter await redis.hincrby("supa-edge-counter", deno_region, 1); } else { // Increment localhost counter await redis.hincrby("supa-edge-counter", "localhost", 1); } // Get all values const counterHash: Record | null = await redis.hgetall( "supa-edge-counter" ); const counters = Object.entries(counterHash!) .sort(([, a], [, b]) => b - a) // sort desc .reduce( (r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v }, }), { total: 0, regions: {}, } ); return new Response(JSON.stringify({ counters }), { status: 200 }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 200, }); } }); ``` ---------------------------------------- TITLE: Next.js App Router Home Page with Upstash Redis Counter DESCRIPTION: This TypeScript React component for `/app/page.tsx` demonstrates how to integrate Upstash Redis to create a simple page view counter. It initializes the Redis client, increments a key named 'counter', and displays the current count on the page. SOURCE: https://upstash.com/docs/redis/quickstarts/nextjs-app-router.mdx LANGUAGE: tsx CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: Upstash Redis Environment Variables for Next.js App DESCRIPTION: This code block shows the required environment variables for connecting to an Upstash Redis database. `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` should be replaced with your actual credentials obtained from the Upstash Console. SOURCE: https://upstash.com/docs/redis/quickstarts/nextjs-app-router.mdx LANGUAGE: plaintext CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Initialize Upstash Redis Client with Direct Configuration DESCRIPTION: This TypeScript example demonstrates how to initialize the Upstash Redis client by directly providing the REST URL and token. It then performs an asynchronous `get` operation to retrieve data from Redis, logging the result or any encountered errors. SOURCE: https://upstash.com/docs/redis/howto/connectwithupstashredis.mdx LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN" }); (async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` ---------------------------------------- TITLE: Implement Basic Rate Limiting with Upstash Ratelimit DESCRIPTION: This TypeScript example demonstrates how to initialize `@upstash/ratelimit` with an Upstash Redis instance, configure a sliding window limiter, and apply it to an endpoint to control request rates. It shows how to check for rate limit success and handle blocked requests. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: ts CODE: ``` import { Ratelimit } from "@upstash/ratelimit"; // for deno: see above import { Redis } from "@upstash/redis"; // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, /** * Optional prefix for the keys used in redis. This is useful if you want to share a redis * instance with other applications and want to avoid key collisions. The default prefix is * "@upstash/ratelimit" */ prefix: "@upstash/ratelimit", }); // Use a constant string to limit all requests with a single ratelimit // Or use a userID, apiKey or ip address for individual limits. const identifier = "api"; const { success } = await ratelimit.limit(identifier); if (!success) { return "Unable to process at this time"; } doExpensiveCalculation(); return "Here you go!"; ``` ---------------------------------------- TITLE: Perform Basic Redis Operations (Set/Get) with Upstash Client DESCRIPTION: This example demonstrates how to perform fundamental Redis `set` and `get` operations using both synchronous and asynchronous `upstash-redis` clients. It shows the process of initializing the client, typically from environment variables, and then executing commands. Pay close attention to the use of the `await` keyword for handling asynchronous operations correctly. SOURCE: https://upstash.com/docs/redis/sdks/py/gettingstarted.mdx LANGUAGE: python CODE: ``` from upstash_redis import Redis redis = Redis.from_env() def main(): redis.set("a", "b") print(redis.get("a")) # or for async context: from upstash_redis.asyncio import Redis redis = Redis.from_env() async def main(): await redis.set("a", "b") print(await redis.get("a")) ``` ---------------------------------------- TITLE: Connect to Upstash Redis using jedis (Java) DESCRIPTION: This example demonstrates connecting to an Upstash Redis database using the `jedis` library in Java. It creates a Jedis instance with the endpoint, port, and SSL enabled, authenticates with the password, and then sets and retrieves a string value. SOURCE: https://upstash.com/docs/redis/howto/connectclient.mdx LANGUAGE: java CODE: ``` Jedis jedis = new Jedis("YOUR_ENDPOINT", "YOUR_PORT", true); jedis.auth("YOUR_PASSWORD"); jedis.set("foo", "bar"); String value = jedis.get("foo"); System.out.println(value); ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables DESCRIPTION: These commands set the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables, which are required to connect to your Upstash Redis database. Replace placeholders with your actual credentials. SOURCE: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime.mdx LANGUAGE: shell CODE: ``` export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Set Environment Variables for Cloudflare Worker (Wrangler) DESCRIPTION: Commands to set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` as secrets in a Cloudflare Worker project using the `wrangler secret put` command-line tool. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: bash CODE: ``` npx wrangler secret put UPSTASH_REDIS_REST_URL ``` LANGUAGE: bash CODE: ``` npx wrangler secret put UPSTASH_REDIS_REST_TOKEN ``` ---------------------------------------- TITLE: Python Multithreaded Web Scraper with Redis Caching DESCRIPTION: This comprehensive Python code implements a multithreaded web scraper. It uses `threading` to process URL groups concurrently, `requests` for HTTP requests, and `upstash-redis` for caching. The `Scraper` class checks Redis for cached responses before making new HTTP requests, storing new responses in Redis to optimize performance and reduce redundant fetches across threads. SOURCE: https://upstash.com/docs/redis/tutorials/python_multithreading.mdx LANGUAGE: python CODE: ``` import threading import requests from upstash_redis import Redis from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Initialize Redis client redis = Redis.from_env() # Group URLs by thread, with one or two overlapping URLs across groups urls_to_scrape_groups = [ [ 'https://httpbin.org/delay/1', 'https://httpbin.org/delay/4', 'https://httpbin.org/delay/2', 'https://httpbin.org/delay/5', 'https://httpbin.org/delay/3', ], [ 'https://httpbin.org/delay/5', # Overlapping URL 'https://httpbin.org/delay/6', 'https://httpbin.org/delay/7', 'https://httpbin.org/delay/2', # Overlapping URL 'https://httpbin.org/delay/8', ], [ 'https://httpbin.org/delay/3', # Overlapping URL 'https://httpbin.org/delay/9', 'https://httpbin.org/delay/10', 'https://httpbin.org/delay/4', # Overlapping URL 'https://httpbin.org/delay/11', ], ] class Scraper(threading.Thread): def __init__(self, urls): threading.Thread.__init__(self) self.urls = urls self.results = {} def run(self): for url in self.urls: cache_key = f"url:{url}" # Attempt to retrieve cached response cached_response = redis.get(cache_key) if cached_response: print(f"[CACHE HIT] {self.name} - URL: {url}") self.results[url] = cached_response continue # Skip to the next URL if cache is found # If no cache, perform the HTTP request print(f"[FETCHING] {self.name} - URL: {url}") response = requests.get(url) if response.status_code == 200: self.results[url] = response.text # Store the response in Redis cache redis.set(cache_key, response.text) else: print(f"[ERROR] {self.name} - Failed to retrieve {url}") self.results[url] = None def main(): threads = [] for urls in urls_to_scrape_groups: scraper = Scraper(urls) threads.append(scraper) scraper.start() # Wait for all threads to complete for scraper in threads: scraper.join() print("\nScraping results:") for scraper in threads: for url, result in scraper.results.items(): print(f"Thread {scraper.name} - URL: {url} - Response Length: {len(result) if result else 'Failed'}") if __name__ == "__main__": main() ``` ---------------------------------------- TITLE: Next.js Home Page Redis Counter Implementation DESCRIPTION: This TypeScript/React code demonstrates how to modify the Next.js home page (`/app/page.tsx`) to interact with Redis. It initializes a Redis client, increments a 'counter' key, and displays the current count, showcasing basic data retrieval and update operations. SOURCE: https://upstash.com/docs/redis/tutorials/nextjs_with_redis.mdx LANGUAGE: tsx CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: FastAPI Session Management Application with Redis DESCRIPTION: Implements a FastAPI application demonstrating user session management using Upstash Redis. It includes endpoints for user login, profile access with sliding session expiration, and logout, all leveraging Redis for storing and managing session data. SOURCE: https://upstash.com/docs/redis/tutorials/python_session.mdx LANGUAGE: Python CODE: ``` from fastapi import FastAPI, Response, Cookie, HTTPException from pydantic import BaseModel from upstash_redis import Redis from dotenv import load_dotenv import uuid # Load environment variables load_dotenv() redis = Redis.from_env() app = FastAPI() SESSION_TIMEOUT_SECONDS = 900 # 15 minutes # Define the request body model for login class LoginRequest(BaseModel): username: str @app.post("/login/") async def login(request: LoginRequest, response: Response): session_id = str(uuid.uuid4()) redis.hset(f"session:{session_id}", values={"user": request.username, "status": "active"}) redis.expire(f"session:{session_id}", SESSION_TIMEOUT_SECONDS) response.set_cookie(key="session_id", value=session_id, httponly=True) return {"message": "Logged in successfully", "session_id": session_id} @app.get("/profile/") async def get_profile(session_id: str = Cookie(None)): if not session_id: raise HTTPException(status_code=403, detail="No session cookie found") session_data = redis.hgetall(f"session:{session_id}") if not session_data: response = Response() response.delete_cookie(key="session_id") # Clear the expired cookie raise HTTPException(status_code=404, detail="Session expired") # Update the session expiration time (sliding expiration) redis.expire(f"session:{session_id}", SESSION_TIMEOUT_SECONDS) return {"session_id": session_id, "session_data": session_data} @app.post("/logout/") async def logout(response: Response, session_id: str = Cookie(None)): if session_id: redis.delete(f"session:{session_id}") response.delete_cookie(key="session_id") return {"message": "Logged out successfully"} ``` ---------------------------------------- TITLE: Set Upstash Redis Environment Variables DESCRIPTION: These bash commands export the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables. These variables are crucial for the Node.js application to authenticate and connect to the Upstash Redis database. SOURCE: https://upstash.com/docs/redis/quickstarts/koyeb.mdx LANGUAGE: bash CODE: ``` export UPSTASH_REDIS_REST_URL="" export UPSTASH_REDIS_REST_TOKEN="" ``` ---------------------------------------- TITLE: Set Upstash Redis Environment Variables (Shell) DESCRIPTION: These shell commands set the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables. These variables are crucial for the Python application to establish a connection with the Upstash Redis database. SOURCE: https://upstash.com/docs/redis/tutorials/python_url_shortener.mdx LANGUAGE: shell CODE: ``` export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Producer Function for Employee Registration Queue DESCRIPTION: Illustrates a JavaScript AWS Lambda function acting as a producer, using the Bull library to add new employee registration events to a Redis-backed task queue. It configures the queue with Redis connection details (host, port, password) and specific settings to manage job processing intervals, and returns a success message upon enqueuing the event. SOURCE: https://upstash.com/docs/redis/tutorials/job_processing.mdx LANGUAGE: JavaScript CODE: ``` var Queue = require("bull"); var settings = { stalledInterval: 300000, // How often check for stalled jobs (use 0 for never checking). guardInterval: 5000, // Poll interval for delayed jobs and added jobs. drainDelay: 300, // A timeout for when the queue is in drained state (empty waiting for jobs). }; module.exports.hello = async (event) => { var taskQueue = new Queue( "employee registration", { redis: { port: 32016, host: "us1-upward-ant-32016.upstash.io", password: "ake4ff120d6b4216df220736be7eab087", tls: {}, }, }, settings ); await taskQueue.add({ event: event }); // TODO save the employee record to a database return { message: "New employee event enqueued! 34", event }; }; ``` ---------------------------------------- TITLE: Connect to Upstash Redis using redis-py (Python) DESCRIPTION: This example illustrates connecting to an Upstash Redis database using the `redis-py` library in Python. It initializes a Redis client with the host, port, password, and enables SSL, then performs a `set` and `get` operation. SOURCE: https://upstash.com/docs/redis/howto/connectclient.mdx LANGUAGE: python CODE: ``` import redis r = redis.Redis( host= 'YOUR_ENDPOINT', port= 'YOUR_PORT', password= 'YOUR_PASSWORD', ssl=True) r.set('foo','bar') print(r.get('foo')) ``` ---------------------------------------- TITLE: Upstash Redis Environment Variables Configuration DESCRIPTION: This snippet illustrates how to configure the essential environment variables for connecting to an Upstash Redis database. It includes placeholders for the REST URL and Token, which are required for authentication and API access. SOURCE: https://upstash.com/docs/redis/tutorials/nextjs_with_redis.mdx LANGUAGE: shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Separate Client Instances for Read and Write Operations DESCRIPTION: Demonstrates a common pattern where write and read requests might originate from different client instances or API endpoints. This setup, without explicit sync token management, can lead to read-after-write consistency issues on read replicas. The example shows a write function, a read function, and their sequential invocation. SOURCE: https://upstash.com/docs/redis/howto/readyourwrites.mdx LANGUAGE: TypeScript CODE: ``` export const writeRequest = async () => { const redis = Redis.fromEnv(); const randomKey = nanoid(); await redis.set(randomKey, "value"); return randomKey; }; export const readRequest = async (randomKey: string) => { const redis = Redis.fromEnv(); const value = await redis.get(randomKey); return value; }; const randomKey = await writeRequest(); await readRequest(randomKey); ``` ---------------------------------------- TITLE: Implement FastAPI Application with Fixed Window Rate Limiting DESCRIPTION: This Python script defines a FastAPI application (`main.py`) that integrates Upstash Redis for fixed window rate limiting. It includes an `/expensive_calculation` endpoint protected by a rate limiter, a simulated expensive function, and a test function to demonstrate rate limiting behavior by making multiple requests. SOURCE: https://upstash.com/docs/redis/tutorials/python_rate_limiting.mdx LANGUAGE: python CODE: ``` from fastapi import FastAPI, HTTPException from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis from dotenv import load_dotenv import requests # Load environment variables from .env file load_dotenv() # Initialize the FastAPI app app = FastAPI() # Initialize Redis client redis = Redis.from_env() # Create a rate limiter that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=redis, limiter=FixedWindow(max_requests=10, window=10), # 10 requests per 10 seconds prefix="@upstash/ratelimit" ) @app.get("/expensive_calculation") def expensive_calculation(): identifier = "api" # Common identifier for rate limiting all users equally response = ratelimit.limit(identifier) if not response.allowed: raise HTTPException(status_code=429, detail="Rate limit exceeded. Please try again later.") # Placeholder for a resource-intensive operation result = do_expensive_calculation() return {"message": "Here is your result", "result": result} # Simulated function for an expensive calculation def do_expensive_calculation(): return "Expensive calculation result" # Test function to check rate limiting def test_rate_limiting(): url = "http://127.0.0.1:8000/expensive_calculation" success_count = 0 fail_count = 0 # Attempt 15 requests in quick succession for i in range(15): response = requests.get(url) if response.status_code == 200: success_count += 1 print(f"Request {i+1}: Success - {response.json()['message']}") elif response.status_code == 429: fail_count += 1 print(f"Request {i+1}: Failed - Rate limit exceeded") # Small delay to avoid flooding print("\nTest Summary:") print(f"Total Successful Requests: {success_count}") print(f"Total Failed Requests due to Rate Limit: {fail_count}") if __name__ == "__main__": # Run the FastAPI app in a separate thread or terminal with: # uvicorn main:app --reload # To test rate limiting after the server is running test_rate_limiting() ``` ---------------------------------------- TITLE: Implement Multi-Region Ratelimiting with Upstash DESCRIPTION: This code demonstrates how to set up `MultiRegionRatelimit` using multiple Redis instances, enabling low-latency ratelimiting for users across different geographical regions. It highlights the initialization with an array of Redis clients and the use of `slidingWindow` for the limiter, ensuring distributed state replication via CRDTs. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/features.mdx LANGUAGE: ts CODE: ``` import { MultiRegionRatelimit } from "@upstash/ratelimit"; // for deno: see above import { Redis } from "@upstash/redis"; // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }), new Redis({ /* auth */ }), ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), analytics: true, }); // Use a constant string to limit all requests with a single ratelimit // Or use a userID, apiKey or ip address for individual limits. const identifier = "api"; const { success } = await ratelimit.limit(identifier); ``` ---------------------------------------- TITLE: Cloudflare Worker Leaderboard API Logic (`index.js`) DESCRIPTION: Main JavaScript code for the Cloudflare Worker, handling incoming requests. It routes GET requests to `getLeaderboard` and POST requests to `addScore`, interacting with Upstash Redis and leveraging Cloudflare's edge caching. SOURCE: https://upstash.com/docs/redis/tutorials/edge_leaderboard.mdx LANGUAGE: javascript CODE: ``` addEventListener("fetch", (event) => { event.respondWith(handleRequest(event.request)); }); async function handleRequest(request) { if (request.method === "GET") { return getLeaderboard(); } else if (request.method === "POST") { return addScore(request); } else { return new Response("Invalid Request!"); } } async function getLeaderboard() { let url = "https://us1-full-bug-31874.upstash.io/zrevrange/scores/0/1000/WITHSCORES/?_token=" + TOKEN; let res = await fetch(new Request(url), { cf: { cacheTtl: 10, cacheEverything: true, cacheKey: url, }, }); return res; } async function addScore(request) { const { searchParams } = new URL(request.url); let player = searchParams.get("player"); let score = searchParams.get("score"); let url = "https://us1-full-bug-31874.upstash.io/zadd/scores/" + score + "/" + player + "?_token=" + TOKEN; let res = await fetch(url); return new Response(await res.text()); } ``` ---------------------------------------- TITLE: Deploy Serverless Redis HTTP (SRH) with Docker Compose DESCRIPTION: This Docker Compose configuration sets up both a Redis server and an SRH instance. SRH is configured to connect to the Redis service within the same Docker network, making it suitable for local development or Kubernetes-like environments where services need to communicate internally. SOURCE: https://upstash.com/docs/redis/sdks/ts/developing.mdx LANGUAGE: yml CODE: ``` version: "3" services: redis: image: redis ports: - "6379:6379" serverless-redis-http: ports: - "8079:80" image: hiett/serverless-redis-http:latest environment: SRH_MODE: env SRH_TOKEN: example_token SRH_CONNECTION_STRING: "redis://redis:6379" # Using `redis` hostname since they're in the same Docker network. ``` ---------------------------------------- TITLE: Redis Connection Error Symptom Output DESCRIPTION: Displays the typical error message and stack trace received when a new client fails to connect to Redis due to exceeding the maximum concurrent connections. SOURCE: https://upstash.com/docs/redis/troubleshooting/max_concurrent_connections.mdx LANGUAGE: text CODE: ``` "message" : "[ioredis] Unhandled error event:\nReplyError: ERR max concurrent connections exceeded\r\nat Object.onceWrapper (events.js:286:20)\r\nat Socket.emit (events.js:203:15)\r at Socket.EventEmitter.emit (domain.js:448:20)\r\nat TCPConnectWrap.afterConnect [as oncomplete] (net.js:1093:10)\n" ``` ---------------------------------------- TITLE: Upstash Redis Daily Request Limit Exceeded Error Message DESCRIPTION: This snippet displays the specific error message returned by Upstash Redis when a database exceeds its configured maximum daily request count. This indicates that the application has sent more commands than allowed within a 24-hour period. SOURCE: https://upstash.com/docs/redis/troubleshooting/max_daily_request_limit.mdx LANGUAGE: Redis Error CODE: ``` ReplyError: ERR max daily request limit exceeded ``` ---------------------------------------- TITLE: Cache Data with Laravel Cache::remember DESCRIPTION: Example of using Laravel's Cache::remember method. This method retrieves data from the cache by key; if not found, it executes the provided closure to fetch the data (e.g., all todos) and stores the result in the cache for a specified duration. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: php CODE: ``` $value = Cache::remember('todos', $seconds, function () { return Todo::all(); }); ``` ---------------------------------------- TITLE: Configure Environment Variables DESCRIPTION: Illustrates how to set up the `.env` file with placeholders for `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`. These environment variables are crucial for the Lambda function to connect to the Upstash Redis database. SOURCE: https://upstash.com/docs/redis/tutorials/rate-limiting.mdx LANGUAGE: shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Create Next.js API Route with Upstash Redis Counter DESCRIPTION: TypeScript code for a Next.js API route (`/app/api/hello/route.ts`) that demonstrates connecting to Upstash Redis, incrementing a counter, and returning the current count as a JSON response. It also forces dynamic rendering. SOURCE: https://upstash.com/docs/redis/quickstarts/vercel-functions-app-router.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis"; import { NextResponse } from "next/server"; const redis = Redis.fromEnv(); export async function GET() { const count = await redis.incr("counter"); return NextResponse.json({ count }); } export const dynamic = 'force-dynamic' ``` ---------------------------------------- TITLE: Go Lambda Function for Page View Counter DESCRIPTION: The core Go code for the AWS Lambda function. It imports necessary packages for AWS Lambda events, JSON encoding, and Redis interaction. The `handler` function connects to Redis, increments a 'count' key, and returns the updated count in a JSON response. Placeholder values for Redis endpoint and password must be replaced. SOURCE: https://upstash.com/docs/redis/tutorials/goapi.mdx LANGUAGE: Go CODE: ``` package main import ( "context" "encoding/json" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/go-redis/redis/v8" "strconv" ) var ctx = context.Background() type MyResponse struct { Count string `json:"count:"` } var rdb = redis.NewClient(&redis.Options{ Addr: "YOUR_REDIS_ENDPOINT", Password: "YOUR_REDIS_PASSWORD", DB: 0, }) func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { count, err := rdb.Incr(ctx, "count").Result() if err != nil { panic(err) } response := &MyResponse{ Count: strconv.FormatInt(count, 10), } body, err := json.Marshal(response) return events.APIGatewayProxyResponse{ Headers: map[string]string{"Content-Type": "application/json"}, Body: string(body), StatusCode: 200, }, nil } func main() { lambda.Start(handler) } ``` ---------------------------------------- TITLE: Initialize Upstash Redis Client in Vercel DESCRIPTION: This code snippet demonstrates how to initialize an Upstash Redis client within a Vercel application using `Redis.fromEnv()`. It automatically reads `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from environment variables, allowing for seamless connection and basic data operations like setting and getting a key. SOURCE: https://upstash.com/docs/redis/howto/vercelintegration.mdx LANGUAGE: ts CODE: ``` const { Redis } = require("@upstash/redis"); module.exports = async (req, res) => { /** * Redis.fromEnv() will read the following from environment variables: * - UPSTASH_REDIS_REST_URL * - UPSTASH_REDIS_REST_TOKEN */ const redis = Redis.fromEnv(); await redis.set("foo", "bar"); const bar = await redis.get("foo"); res.json({ body: `foo: ${bar}`, }); }; ``` ---------------------------------------- TITLE: Create FastAPI Application with Upstash Redis Counter DESCRIPTION: Defines a basic FastAPI application in `main.py`. It initializes an Upstash Redis client using environment variables and creates a root endpoint that increments a counter in Redis on each access, returning the current count. SOURCE: https://upstash.com/docs/redis/quickstarts/fastapi.mdx LANGUAGE: python CODE: ``` from fastapi import FastAPI from upstash_redis import Redis app = FastAPI() redis = Redis.from_env() @app.get("/") def read_root(): count = redis.incr('counter') return {"count": count} ``` ---------------------------------------- TITLE: Implement AWS Lambda Rate Limiting Function DESCRIPTION: Provides the JavaScript code for `handler.js`, which defines an AWS Lambda function. This function utilizes `@upstash/ratelimit` and `@upstash/redis` to implement IP-based rate limiting, checking the client's source IP and returning appropriate HTTP status codes (200 for success, 429 for rate-limited). SOURCE: https://upstash.com/docs/redis/tutorials/rate-limiting.mdx LANGUAGE: javascript CODE: ``` const { Ratelimit } = require("@upstash/ratelimit"); const { Redis } = require("@upstash/redis"); const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), prefix: "@upstash/ratelimit", analytics: true, }); exports.ratelimit = async (event) => { const identifier = event.requestContext.http.sourceIP; const { success, limit, remaining, pending } = await ratelimit.limit( identifier ); const response = { success: success, limit: limit, remaining: remaining, }; // pending is a promise for handling the analytics submission await pending; if (!success) { return { statusCode: 429, body: JSON.stringify(response), }; } return { statusCode: 200, body: JSON.stringify(response), }; }; ``` ---------------------------------------- TITLE: Express.js Application with Redis Session Management DESCRIPTION: This comprehensive JavaScript code defines an Express.js web application that uses `express-session` and `connect-redis` for managing user sessions. It initializes a Redis client (placeholder for connection details), configures the session middleware to store sessions in Redis, and defines routes to track page views per session. This demonstrates how to integrate Redis for stateless session handling in a serverless environment. SOURCE: https://upstash.com/docs/redis/tutorials/cloud_run_sessions.mdx LANGUAGE: javascript CODE: ``` var express = require("express"); var parseurl = require("parseurl"); var session = require("express-session"); const redis = require("redis"); var RedisStore = require("connect-redis")(session); var client = redis.createClient({ // REPLACE HERE }); var app = express(); app.use( session({ store: new RedisStore({ client: client }), secret: "forest squirrel", resave: false, saveUninitialized: true, }) ); app.use(function (req, res, next) { if (!req.session.views) { req.session.views = {}; } // get the url pathname var pathname = parseurl(req).pathname; // count the views req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; next(); }); app.get("/", function (req, res, next) { res.send("you viewed this page " + req.session.views["/"] + " times"); }); app.get("/foo", function (req, res, next) { res.send("you viewed this page " + req.session.views["/foo"] + " times"); }); app.get("/bar", function (req, res, next) { res.send("you viewed this page " + req.session.views["/bar"] + " times"); }); app.listen(8080, function () { console.log("Example app listening on port 8080!"); }); ``` ---------------------------------------- TITLE: Define AWS CDK Stack for Counter Lambda DESCRIPTION: This TypeScript code defines the AWS CDK stack responsible for deploying the counter Lambda function. It configures the Lambda with Node.js 20.x runtime, sets environment variables for Upstash Redis credentials, and creates a Function URL to make the Lambda publicly accessible. SOURCE: https://upstash.com/docs/redis/quickstarts/aws-lambda.mdx LANGUAGE: typescript CODE: ``` import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new nodejs.NodejsFunction(this, 'CounterFunction', { entry: 'api/counter.ts', handler: 'handler', runtime: lambda.Runtime.NODEJS_20_X, environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, bundling: { format: nodejs.OutputFormat.ESM, target: "node20", nodeModules: ['@upstash/redis'], }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ``` ---------------------------------------- TITLE: Define Python Dependencies for API DESCRIPTION: Specifies the `upstash-redis` library as a required dependency for the Python serverless function. This file will be used by pip during the Lambda bundling process. SOURCE: https://upstash.com/docs/redis/tutorials/pythonapi.mdx LANGUAGE: txt CODE: ``` upstash-redis ``` ---------------------------------------- TITLE: Install Upstash Redis client package DESCRIPTION: Installs the `@upstash/redis` npm package, which is the client library required for interacting with Upstash Redis. SOURCE: https://upstash.com/docs/redis/quickstarts/ion.mdx LANGUAGE: shell CODE: ``` npm install @upstash/redis ``` ---------------------------------------- TITLE: Redis KEYS Command API Documentation DESCRIPTION: Detailed API documentation for the Redis `KEYS` command, including its purpose, arguments, and response format. It also highlights a critical warning about its performance implications in production environments, advising the use of `SCAN` instead. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/generic/keys.mdx LANGUAGE: APIDOC CODE: ``` KEYS Command: Description: Returns all keys matching pattern. Warning: This command may block the DB for a long time, depending on its size. We advice against using it in production. Use SCAN instead. Arguments: match: Type: string Required: true Description: A glob-style pattern. Use * to match all keys. Response: Type: string[] Required: true Description: Array of keys matching the pattern. ``` ---------------------------------------- TITLE: Connect to Upstash Redis using ioredis (JavaScript) DESCRIPTION: This example shows how to connect to an Upstash Redis database using the `ioredis` library in Node.js. It establishes a secure connection using the provided endpoint, port, and password, then demonstrates setting and retrieving a key-value pair. SOURCE: https://upstash.com/docs/redis/howto/connectclient.mdx LANGUAGE: javascript CODE: ``` const Redis = require("ioredis"); let client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); await client.set("foo", "bar"); let x = await client.get("foo"); console.log(x); ``` ---------------------------------------- TITLE: Connect to Upstash Redis using redis-cli DESCRIPTION: This snippet demonstrates how to connect to an Upstash Redis database using the `redis-cli` command-line interface. It shows examples of basic Redis commands like `set`, `get`, and `incr` to interact with the database. Users need to replace placeholders like PASSWORD, ENDPOINT, and PORT with their actual database credentials. SOURCE: https://upstash.com/docs/redis/overall/getstarted.mdx LANGUAGE: bash CODE: ``` > redis-cli --tls -a PASSWORD -h ENDPOINT -p PORT ENDPOINT:PORT> set counter 0 OK ENDPOINT:PORT> get counter "0" ENDPOINT:PORT> incr counter (int) 1 ENDPOINT:PORT> incr counter (int) 2 ``` ---------------------------------------- TITLE: Configure Laravel Cache Store to Redis in .env DESCRIPTION: Environment variables to configure Laravel's caching system to use Redis as the default cache store. It specifies CACHE_STORE as 'redis' and sets a dedicated Redis database for caching. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: .env CODE: ``` CACHE_STORE="redis" REDIS_CACHE_DB="0" ``` ---------------------------------------- TITLE: Apply fixed-window rate limit for all routes using Authorization header (JSON) DESCRIPTION: This configuration snippet demonstrates how to enable the Strapi Upstash Rate Limit plugin and apply a fixed-window rate limit across all routes ('*') for both GET and POST methods. The rate limit is identified by the 'Authorization' header, allowing 10 requests within a 20-second window. SOURCE: https://upstash.com/docs/redis/integrations/ratelimit/strapi/configurations.mdx LANGUAGE: json CODE: ``` { "strapi-plugin-upstash-ratelimit":{ "enabled":true, "resolve":"./src/plugins/strapi-plugin-upstash-ratelimit", "config":{ "enabled":true, "token":"process.env.UPSTASH_REDIS_REST_TOKEN", "url":"process.env.UPSTASH_REDIS_REST_URL", "strategy":[ { "methods":[ "GET", "POST" ], "path":"*", "identifierSource":"header.Authorization", "limiter":{ "algorithm":"fixed-window", "tokens":10, "window":"20s" } } ], "prefix":"@strapi" } } } ``` ---------------------------------------- TITLE: Set Environment Variables for Redis and Weather API DESCRIPTION: Configures environment variables required for connecting to Upstash Redis (URL and token) and for authenticating with the external Weather API. These variables are crucial for the application to function correctly and securely. SOURCE: https://upstash.com/docs/redis/tutorials/python_fastapi_caching.mdx LANGUAGE: shell CODE: ``` export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= export WEATHER_API_KEY= ``` ---------------------------------------- TITLE: Initialize Upstash Redis Client from Environment Variables DESCRIPTION: This TypeScript example shows how to initialize the Upstash Redis client by automatically loading configuration from environment variables (`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`). It then performs an asynchronous `get` operation to retrieve data from Redis, logging the result or any encountered errors. SOURCE: https://upstash.com/docs/redis/howto/connectwithupstashredis.mdx LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv()(); (async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` ---------------------------------------- TITLE: Demonstrate Auto-Pipelining with Async and Batch Operations DESCRIPTION: This example illustrates how auto-pipelining handles asynchronous Redis commands and batch requests. Commands like `hincrby` are added to the pipeline, and multiple `hget` calls are batched using `Promise.all`, resulting in a single Redis `PIPELINE` command execution upon `await`. SOURCE: https://upstash.com/docs/redis/sdks/ts/pipelining/auto-pipeline.mdx LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv({ latencyLogging: false, enableAutoPipelining: true }); // async call to redis. Not executed right away, instead // added to the pipeline redis.hincrby("Brooklyn", "visited", 1); // making requests in batches const brooklynInfo = Promise.all([ redis.hget("Brooklyn", "coordinates"), redis.hget("Brooklyn", "population") ]); // when we call await, the three commands are executed // as a pipeline automatically. A single PIPELINE command // is executed instead of three requests and the results // are returned: const [ coordinates, population ] = await brooklynInfo; ``` ---------------------------------------- TITLE: Initialize Upstash Redis Client from Environment Variables DESCRIPTION: This snippet illustrates how to initialize both synchronous and asynchronous `upstash-redis` clients by automatically loading credentials from environment variables. The client expects `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` to be set in the environment. This approach is highly recommended for cleaner code, enhanced security, and easier management of credentials across different deployment environments. SOURCE: https://upstash.com/docs/redis/sdks/py/gettingstarted.mdx LANGUAGE: python CODE: ``` # for sync use from upstash_redis import Redis redis = Redis.from_env() # for async use from upstash_redis.asyncio import Redis redis = Redis.from_env() ``` ---------------------------------------- TITLE: Initialize BullMQ Queue with Upstash Redis Connection DESCRIPTION: This JavaScript snippet demonstrates how to import the Queue class from 'bullmq' and initialize a new queue. It configures the queue to connect to an Upstash Redis instance using provided host, port, and password. The example also shows an asynchronous function to add multiple jobs to the created queue. SOURCE: https://upstash.com/docs/redis/integrations/bullmq.mdx LANGUAGE: javascript CODE: ``` import { Queue } from 'bullmq'; const myQueue = new Queue('foo', { connection: { host: "UPSTASH_REDIS_ENDPOINT", port: 6379, password: "UPSTASH_REDIS_PASSWORD", tls: {} }}); async function addJobs() { await myQueue.add('myJobName', { foo: 'bar' }); await myQueue.add('myJobName', { qux: 'baz' }); } await addJobs(); ``` ---------------------------------------- TITLE: Enable Global Caching and Opt-Out for DrizzleORM Queries DESCRIPTION: Shows how to configure DrizzleORM for global caching, where all queries read from the cache by default. It also illustrates how to explicitly turn off caching for a specific query even when global caching is active. SOURCE: https://upstash.com/docs/redis/integrations/drizzle.mdx LANGUAGE: typescript CODE: ``` const db = drizzle(process.env.DB_URL!, { cache: upstashCache({ global: true }), }) // 👇 reads from cache (no more explicit `$withCache()`) await db.select().from(users) ``` LANGUAGE: typescript CODE: ``` await db.select().from(users).$withCache(false) ``` ---------------------------------------- TITLE: Cross-Client Read Your Writes Synchronization in TypeScript DESCRIPTION: Illustrates how to manually propagate the `readYourWritesSyncToken` between different client instances to ensure read-after-write consistency. The token is obtained from the Redis client after a write operation and then passed to another client instance, where it's set before a read operation. This pattern is essential for scenarios where writes and subsequent reads might occur from separate application components or services. For Python users, a similar approach applies using `Redis._sync_token`. SOURCE: https://upstash.com/docs/redis/howto/readyourwrites.mdx LANGUAGE: TypeScript CODE: ``` export const writeRequest = async () => { const redis = Redis.fromEnv(); const randomKey = nanoid(); await redis.set(randomKey, "value"); // Get the token **after** making the write const token = redis.readYourWritesSyncToken; return { randomKey, token }; }; export const readRequest = async ( randomKey: string, token: string | undefined ) => { const redis = Redis.fromEnv(); // Set the token **before** making the read redis.readYourWritesSyncToken = token; const value = await redis.get(randomKey); return value; }; const { randomKey, token } = await writeRequest(); await readRequest(randomKey, token); ``` ---------------------------------------- TITLE: Implement Serverless Counter Function in Node.js DESCRIPTION: JavaScript code for `handler.js` defining a serverless function. It initializes the Upstash Redis client, increments a 'counter' key, and returns the current count as a JSON string. SOURCE: https://upstash.com/docs/redis/tutorials/using_serverless_framework.mdx LANGUAGE: js CODE: ``` const { Redis } = require('@upstash/redis'); const redis = Redis.fromEnv(); exports.counter = async (event) => { const count = await redis.incr("counter"); return { statusCode: 200, body: JSON.stringify('Counter: ' + count), }; }; ``` ---------------------------------------- TITLE: Initialize Upstash Redis with Explicit Credentials DESCRIPTION: This TypeScript example demonstrates how to initialize the Upstash Redis client by directly providing the URL and token, offering an alternative to using environment variables via `Redis.fromEnv()`. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: ts CODE: ``` new Redis({ url: "https://****.upstash.io", token: "********", }); ``` ---------------------------------------- TITLE: Python Example for Redis GET DESCRIPTION: Demonstrates setting a key and then retrieving its value using the `GET` command in Python with the Upstash Redis client. This example verifies that the retrieved value matches the one previously set. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/get.mdx LANGUAGE: py CODE: ``` redis.set("key", "value") assert redis.get("key") == "value" ``` ---------------------------------------- TITLE: Define Nuxt Server API Endpoint for Redis DESCRIPTION: Creates a Nuxt server API endpoint (`/api/increment.ts`) that initializes an Upstash Redis client, increments a counter, records the current timestamp as the last call time, and returns the updated count and last called time. It includes error handling for Redis interactions. SOURCE: https://upstash.com/docs/redis/tutorials/nuxtjs_with_redis.mdx LANGUAGE: javascript CODE: ``` import { defineEventHandler } from "h3"; import { Redis } from "@upstash/redis"; // Initialize Redis const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL || "", token: process.env.UPSTASH_REDIS_REST_TOKEN || "" }); export default defineEventHandler(async () => { const identifier = "api_call_counter"; try { // Increment the API call counter and get the updated value const count = await redis.incr(identifier); // Optionally, you can also retrieve other information like the last time it was called const lastCalled = await redis.get("last_called"); const lastCalledAt = lastCalled || "Never"; // Store the current timestamp as the last called time await redis.set("last_called", new Date().toISOString()); // Return the count and last called time return { success: true, count: count, lastCalled: lastCalledAt, }; } catch (error) { console.error("Redis error:", error); return { success: false, message: "Error interacting with Redis", }; } }); ``` ---------------------------------------- TITLE: Backend API: List Features (Next.js, ioredis) DESCRIPTION: This Next.js API endpoint (`/api/list`) retrieves feature requests from an Upstash Redis Sorted Set named 'roadmap'. It fetches features ordered by their vote scores and returns them as a JSON array. The API uses `ioredis` for Redis connectivity. SOURCE: https://upstash.com/docs/redis/tutorials/roadmapvotingapp.mdx LANGUAGE: javascript CODE: ``` import { fixUrl } from "./utils"; import Redis from "ioredis"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); let n = await redis.zrevrange("roadmap", 0, 100, "WITHSCORES"); let result = []; for (let i = 0; i < n.length - 1; i += 2) { let item = {}; item["title"] = n[i]; item["score"] = n[i + 1]; result.push(item); } redis.quit(); res.json({ body: result, }); }; ``` ---------------------------------------- TITLE: Implement Redis Transactions (MULTI/EXEC) in Python DESCRIPTION: This example demonstrates how to use Redis transactions, initiated with `multi()`, to ensure atomicity for a sequence of commands. All commands within a transaction are executed as a single, isolated operation. Similar to pipelines, commands are batched and executed with `.exec()`. SOURCE: https://upstash.com/docs/redis/sdks/py/features.mdx LANGUAGE: python CODE: ``` pipeline = redis.multi() pipeline.set("foo", 1) pipeline.incr("foo") pipeline.get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ``` ---------------------------------------- TITLE: Manually Invalidate DrizzleORM Cache DESCRIPTION: Illustrates how to manually invalidate cached DrizzleORM queries. Caching can be invalidated by specifying table names or custom tags that were associated with the cached queries. SOURCE: https://upstash.com/docs/redis/integrations/drizzle.mdx LANGUAGE: typescript CODE: ``` // 👇 invalidate all queries that use the `users` table await db.$cache?.invalidate({ tables: ["usersTable"] }) // 👇 invalidate all queries by custom tag (defined in previous queries) await db.$cache?.invalidate({ tags: ["custom_key"] }) ``` ---------------------------------------- TITLE: TypeScript Examples for Upstash Redis DEL Command DESCRIPTION: Illustrative TypeScript code examples demonstrating how to use the `redis.del` method to remove keys, including basic usage with multiple arguments and spreading an array of keys. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/generic/del.mdx LANGUAGE: ts CODE: ``` await redis.del("key1", "key2"); ``` LANGUAGE: ts CODE: ``` const keys = ["key1", "key2"]; await redis.del(...keys) ``` ---------------------------------------- TITLE: Define Serverless Counter Lambda Function DESCRIPTION: Implements the core logic for the serverless counter. This TypeScript code uses the Upstash Redis client to increment a 'counter' key and returns the updated count as a JSON string. SOURCE: https://upstash.com/docs/redis/tutorials/api_with_cdk.mdx LANGUAGE: typescript CODE: ``` import { Redis } from '@upstash/redis'; const redis = Redis.fromEnv(); export const handler = async function() { const count = await redis.incr("counter"); return { statusCode: 200, body: JSON.stringify('Counter: ' + count), }; }; ``` ---------------------------------------- TITLE: Implement Location-Aware Greeting Worker with Upstash Redis DESCRIPTION: Defines a Cloudflare Worker in JavaScript that leverages the `@upstash/redis/cloudflare` library. It extracts the client's country from the `cf-ipcountry` header, fetches a corresponding greeting from Upstash Redis, and returns it as a response. A default 'Hello!' is returned if no country-specific greeting is found. SOURCE: https://upstash.com/docs/redis/howto/getstartedcloudflareworkers.mdx LANGUAGE: javascript CODE: ``` // src/index.js import { Redis } from "@upstash/redis/cloudflare"; export default { async fetch(request, env) { const redis = Redis.fromEnv(env); const country = request.headers.get("cf-ipcountry"); if (country) { const greeting = await redis.get(country); if (greeting) { return new Response(greeting); } } return new Response("Hello!"); } } ``` ---------------------------------------- TITLE: Implement Java Lambda Handler with Redis Counter DESCRIPTION: Provides the Java code for the 'Handler' class, which implements 'RequestHandler'. It connects to an Upstash Redis instance, authenticates, increments a 'counter' key, and returns the updated count in an HTTP response. Placeholder values for Redis endpoint and password need to be replaced. SOURCE: https://upstash.com/docs/redis/tutorials/serverless_java_redis.mdx LANGUAGE: java CODE: ``` package com.serverless; import java.util.Map; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import redis.clients.jedis.Jedis; public class Handler implements RequestHandler, ApiGatewayResponse> { @Override public ApiGatewayResponse handleRequest(Map input, Context context) { Jedis jedis = new Jedis("lasting-roughy-29092.upstash.io", 6379, true); jedis.auth("********"); Long value = jedis.incr("counter"); jedis.close(); String message = "Hello World, Count:" + value; return ApiGatewayResponse.builder() .setStatusCode(200) .setObjectBody(message) .build(); } } ``` ---------------------------------------- TITLE: TypeScript Example for Redis EXISTS Usage DESCRIPTION: Illustrates how to use the `redis.exists` method in a TypeScript application to check for key existence and retrieve the count of existing keys. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/generic/exists.mdx LANGUAGE: TypeScript CODE: ``` await redis.set("key1", "value1") await redis.set("key2", "value2") const keys = await redis.exists("key1", "key2", "key3"); console.log(keys) // 2 ``` ---------------------------------------- TITLE: Retrieve Value from Upstash Redis with TypeScript DESCRIPTION: This TypeScript example demonstrates how to use the `redis.get` method to retrieve a value from an Upstash Redis instance. It includes type definition for the expected data structure and shows how to handle cases where the key might not exist. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/string/get.mdx LANGUAGE: ts CODE: ``` type MyType = { a: number; b: string; } const value = await redis.get("key"); if (!value) { // key doesn't exist } else { // value is of type MyType } ``` ---------------------------------------- TITLE: Define Rate Limiting Strategies per Route DESCRIPTION: This section details how to define an array of strategies to apply different rate limits based on HTTP methods, specific paths (with wildcard support), and identifier sources (IP or header). It also includes options for debug logging and the core limiter configuration. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/integrations/strapi/configurations.mdx LANGUAGE: APIDOC CODE: ``` methods: ('GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' |'ALL')[] (required) An array of HTTP methods to apply the rate limit. For example, `["GET", "POST"]` path: string (required) The path to apply the rate limit. You can use wildcards to match multiple routes. For example, `*` matches all routes. Some examples: - `path: "/api/restaurants/:id"` - `path: "/api/restaurants"` identifierSource: string (required) The source to identifiy the user. Requests with the same identifier will be rate limited under the same limit. Available sources are: - `ip`: The IP address of the user. - `header`: The value of a header key. You should pass the source in the `header.` format. For example, `header.Authorization` will use the value of the `Authorization` debug: string Enable debug mode for the route. When enabled, the plugin logs the remaining limits and the block status for each request. limiter: object (required) The limiter configuration for the route. The limiter object has the following properties: - algorithm: 'fixed-window' | 'sliding-window' | 'token-bucket' (required) The rate limit algorithm to use. For more information related to algorithms, see docs here. - `fixed-window`: The fixed-window algorithm divides time into fixed intervals. Each interval has a set limit of allowed requests. When a new interval starts, the count resets. - `sliding-window`: The sliding-window algorithm uses a rolling time frame. It considers requests from the past X time units, continuously moving forward. This provides a smoother distribution of requests over time. - `token-bucket`: The token-bucket algorithm uses a bucket that fills with tokens at a steady rate. Each request consumes a token. If the bucket is empty, requests are denied. This allows for bursts of traffic while maintaining a long-term rate limit. - tokens: number (required) The number of tokens allowed in the time window. - window: string (required) The time window for the rate limit. Available units are "ms" | "s" | "m" | "h" | "d" For example, `20s` means 20 seconds. - refillRate: number The rate at which the bucket refills. This property is only used for the token-bucket algorithm. ``` ---------------------------------------- TITLE: Deploy AWS CDK Application DESCRIPTION: Executes the necessary AWS CDK commands to synthesize the CloudFormation templates, bootstrap the AWS environment for CDK deployment (if not already done), and finally deploy the defined serverless resources to AWS. SOURCE: https://upstash.com/docs/redis/tutorials/pythonapi.mdx LANGUAGE: shell CODE: ``` cdk synth cdk bootstrap cdk deploy ``` ---------------------------------------- TITLE: Initialize Fixed Window Ratelimit with Upstash Redis DESCRIPTION: Demonstrates how to set up a fixed window ratelimiter using the `upstash_ratelimit` library, connected to an Upstash Redis instance. It configures a limit of 10 requests per 10-second window. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-py/algorithms.mdx LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), ) ``` ---------------------------------------- TITLE: Initialize Upstash Redis Client with Explicit Credentials DESCRIPTION: This code demonstrates how to initialize both synchronous and asynchronous `upstash-redis` clients by explicitly providing the Redis REST URL and token. These essential credentials must be securely obtained from your Upstash console. This initialization method is suitable when your credentials are known at compile time or are passed directly into your application. SOURCE: https://upstash.com/docs/redis/sdks/py/gettingstarted.mdx LANGUAGE: python CODE: ``` # for sync client from upstash_redis import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") # for async client from upstash_redis.asyncio import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") ``` ---------------------------------------- TITLE: Python ZRANGE Usage Examples DESCRIPTION: Practical Python examples demonstrating how to use the ZRANGE command with Upstash Redis, covering basic range queries, reverse order, sorting by score, and retrieving scores along with members. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zrange.mdx LANGUAGE: py CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1) == ["a", "b"] ``` LANGUAGE: py CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1, rev=True) == ["c", "b"] ``` LANGUAGE: py CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1, sortby="BYSCORE") == ["a", "b"] ``` LANGUAGE: py CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1, withscores=True) == [("a", 1), ("b", 2)] ``` ---------------------------------------- TITLE: Call Ratelimit Limit Method with Deny List Checks DESCRIPTION: Illustrates how to invoke the `limit` method on the Ratelimit client, providing additional context like IP address, user agent, and country for deny list evaluation. It shows how to await the `pending` promise for asynchronous operations (like analytics) and how to inspect the `success`, `reason`, and `deniedValue` fields to determine if a request was blocked by a deny list. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/traffic-protection.mdx LANGUAGE: tsx CODE: ``` const { success, pending, reason, deniedValue } = ratelimit.limit("userId", { ip: "ip-address", userAgent: "user-agent", country: "country", }); await pending; // await pending if you have analytics enabled console.log(success, reason, deniedValue); // prints: false, "denyList", "ip-address" ``` ---------------------------------------- TITLE: Configure Upstash Redis credentials in Laravel .env DESCRIPTION: Sets the necessary environment variables in Laravel's `.env` file to connect to an Upstash Redis database. This includes the Redis host endpoint, port, and authentication password, ensuring secure access. SOURCE: https://upstash.com/docs/redis/quickstarts/laravel.mdx LANGUAGE: shell CODE: ``` REDIS_HOST="" REDIS_PORT=6379 REDIS_PASSWORD="" ``` ---------------------------------------- TITLE: Cloudflare Worker Upstash Redis Integration DESCRIPTION: This code snippet demonstrates how to initialize the Upstash Redis client within a Cloudflare Worker by leveraging environment variables for secure credential management. It showcases a basic Redis `incr` operation to increment a counter, illustrating fundamental Redis interaction and how to return the result as a JSON response. SOURCE: https://upstash.com/docs/redis/quickstarts/cloudflareworkers.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis/cloudflare"; export interface Env { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; } export default { async fetch( request: Request, env: Env, ctx: ExecutionContext ): Promise { const redis = Redis.fromEnv(env); const count = await redis.incr("counter"); return new Response(JSON.stringify({ count })); } }; ``` LANGUAGE: js CODE: ``` import { Redis } from "@upstash/redis/cloudflare"; export default { async fetch(request, env, ctx) { const redis = Redis.fromEnv(env); const count = await redis.incr("counter"); return new Response(JSON.stringify({ count })); } }; ``` ---------------------------------------- TITLE: Fetch and Display Notifications from Redis DESCRIPTION: React `App.js` component demonstrating the core logic to fetch the latest notification from Upstash Redis using its read-only REST API. It utilizes local storage to keep track of the last seen notification version, preventing repeated display of old messages, and uses `react-toastify` to show the notification. SOURCE: https://upstash.com/docs/redis/tutorials/notification.mdx LANGUAGE: javascript CODE: ``` import logo from "./logo.svg"; import "./App.css"; import { toast, ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import { useEffect } from "react"; function App() { useEffect(() => { async function fetchData() { try { let version = localStorage.getItem("notification-version"); version = version ? version : 0; const response = await fetch( "REPLACE_UPSTASH_REDIS_REST_URL/zrevrangebyscore/messages/+inf/" + version + "/WITHSCORES/LIMIT/0/1", { headers: { Authorization: "Bearer REPLACE_UPSTASH_REDIS_REST_TOKEN", }, } ); const res = await response.json(); const v = parseInt(res.result[1]); if (v) { localStorage.setItem("notification-version", v + 1); } toast(res.result[0]); } catch (e) { console.error(e); } } fetchData(); }); return (
logo

Edit src/App.js and save to reload.

Learn React
); } export default App; ``` ---------------------------------------- TITLE: Cloudflare Worker Greeting Function with Upstash Redis DESCRIPTION: Defines an asynchronous `fetch` handler for a Cloudflare Worker. It initializes an Upstash Redis client, retrieves the client's country from request headers, and fetches a corresponding greeting from Redis. If no country-specific greeting is found, it defaults to 'Hello!'. SOURCE: https://upstash.com/docs/redis/tutorials/cloudflare_workers_with_redis.mdx LANGUAGE: typescript CODE: ``` import { Redis } from '@upstash/redis/cloudflare'; type RedisEnv = { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; }; export default { async fetch(request: Request, env: RedisEnv) { const redis = Redis.fromEnv(env); const country = request.headers.get('cf-ipcountry'); if (country) { const greeting = await redis.get(country); if (greeting) { return new Response(greeting); } } return new Response('Hello!'); }, }; ``` ---------------------------------------- TITLE: Iterate All Members of a Sorted Set with ZSCAN (Python) DESCRIPTION: This Python example demonstrates how to use the `ZSCAN` command to retrieve all members and their scores from a sorted set. It handles pagination by iteratively calling `ZSCAN` with the returned cursor until the iteration is complete. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zscan.mdx LANGUAGE: python CODE: ``` # Get all elements of an ordered set. cursor = 0 results = [] while True: cursor, keys = redis.zscan("myzset", cursor, match="*") results.extend(keys) if cursor == 0: break for key, score in results: print(key, score) ``` ---------------------------------------- TITLE: Remove Key from Cache using Laravel Cache::forget DESCRIPTION: Demonstrates how to remove a specific key from the application cache using Laravel's `Cache::forget` method. This is typically used for cache invalidation after data modification to ensure fresh data is retrieved on subsequent requests. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: php CODE: ``` Cache::forget('todos'); ``` ---------------------------------------- TITLE: Implement Token Bucket Ratelimiting with Upstash Redis DESCRIPTION: Demonstrates how to create a ratelimiter using the token bucket algorithm, configured to refill 5 tokens every 10 seconds with a maximum capacity of 10. Note that multi-regional support is not yet available for this algorithm. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/algorithms.mdx LANGUAGE: ts CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.tokenBucket(5, "10 s", 10), analytics: true, }); ``` ---------------------------------------- TITLE: Execute Multiple Redis Commands via Upstash Pipelining DESCRIPTION: Full `curl` command demonstrating how to send a batch of Redis commands (`SET`, `SETEX`, `INCR`, `ZADD`) to the Upstash `/pipeline` endpoint. This example combines the Redis commands into the JSON request body for a single HTTP request. SOURCE: https://upstash.com/docs/redis/features/restapi.mdx LANGUAGE: shell CODE: ``` curl -X POST https://us1-merry-cat-32748.upstash.io/pipeline \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" \ -d ' [ ["SET", "key1", "valuex"], ["SETEX", "key2", 13, "valuez"], ["INCR", "key1"], ["ZADD", "myset", 11, "item1", 22, "item2"] ] ' ``` ---------------------------------------- TITLE: Configure Upstash Redis Client with Custom Retries DESCRIPTION: This snippet demonstrates how to initialize the `@upstash/redis` client with custom retry options. It allows specifying the maximum number of retries and providing a custom function for exponential backoff, which is useful for handling transient network errors gracefully. SOURCE: https://upstash.com/docs/redis/sdks/ts/retries.mdx LANGUAGE: TypeScript CODE: ``` new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN, retry: { retries: 5, backoff: (retryCount) => Math.exp(retryCount) * 50, }, }); ``` ---------------------------------------- TITLE: Execute Redis Transaction using Upstash TS SDK DESCRIPTION: Illustrates the use of the `multi` method in the Upstash Redis TypeScript SDK for atomic execution of multiple commands. All commands within a transaction are guaranteed to run without interruption from other clients. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/transaction.mdx LANGUAGE: typescript CODE: ``` const tx = redis.multi(); tx.set("foo", "bar"); tx.get("foo"); const res = await tx.exec(); ``` ---------------------------------------- TITLE: Enable Auto-Pipelining for Upstash Redis Client DESCRIPTION: This snippet demonstrates how to enable auto-pipelining when initializing the Upstash Redis client. It shows two common initialization methods: `Redis.fromEnv` for environment variable configuration and direct instantiation with a URL and token. SOURCE: https://upstash.com/docs/redis/sdks/ts/pipelining/auto-pipeline.mdx LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv({ latencyLogging: false, enableAutoPipelining: true }); ``` LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ url: , token: , enableAutoPipelining: true }) ``` ---------------------------------------- TITLE: Define Django View with Redis Counter DESCRIPTION: This Python code defines an `index` view function for the Django application. It connects to the Upstash Redis instance using environment variables and increments a key named 'counter' every time the page is accessed. The function then returns an HTTP response displaying the updated visit count. SOURCE: https://upstash.com/docs/redis/quickstarts/django.mdx LANGUAGE: python CODE: ``` from django.http import HttpResponse from upstash_redis import Redis redis = Redis.from_env() def index(request): count = redis.incr('counter') return HttpResponse(f'Page visited {count} times.') ``` ---------------------------------------- TITLE: Configure DrizzleORM with Custom Upstash Cache Options DESCRIPTION: Advanced configuration for DrizzleORM's Upstash Redis cache, allowing explicit Redis credentials, enabling global caching for all queries by default, and setting custom caching options like expiration time. SOURCE: https://upstash.com/docs/redis/integrations/drizzle.mdx LANGUAGE: typescript CODE: ``` import { upstashCache } from "drizzle-orm/cache/upstash" import { drizzle } from "drizzle-orm/..." const db = drizzle(process.env.DB_URL!, { cache: upstashCache({ // 👇 Redis credentials (optional — can also be pulled from env vars) url: "", token: "", // 👇 Enable caching for all queries (optional, default false) global: true, // 👇 Default cache behavior (optional) config: { ex: 60 }, }), }) ``` ---------------------------------------- TITLE: Implement Upstash Redis Counter Lambda Handler in Python DESCRIPTION: Defines the Python Lambda function (`index.py`) that connects to Upstash Redis, increments a counter, and returns the current count. It uses `Redis.from_env()` to retrieve connection details from environment variables. SOURCE: https://upstash.com/docs/redis/quickstarts/python-aws-lambda.mdx LANGUAGE: python CODE: ``` from upstash_redis import Redis redis = Redis.from_env() def handler(event, context): count = redis.incr('counter') return { 'statusCode': 200, 'body': f'Counter: {count}' } ``` ---------------------------------------- TITLE: Implement Deno Deploy View Counter Handler with Upstash Redis DESCRIPTION: This TypeScript code snippet defines an HTTP server handler for Deno Deploy. It uses the Upstash Redis client to increment a counter key ('deno-counter') for each incoming request (excluding favicon requests) and returns the updated counter value as a JSON response. SOURCE: https://upstash.com/docs/redis/quickstarts/deno-deploy.mdx LANGUAGE: TypeScript CODE: ``` import { serve } from "https://deno.land/std@0.142.0/http/server.ts"; import { Redis } from "https://deno.land/x/upstash_redis@v1.14.0/mod.ts"; serve(async (_req: Request) => { if (!_req.url.endsWith("favicon.ico")) { const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN" }); const counter = await redis.incr("deno-counter"); return new Response(JSON.stringify({ counter }), { status: 200 }); } }); ``` ---------------------------------------- TITLE: Next.js Project Setup and Upstash Redis Installation DESCRIPTION: Commands to initialize a new Next.js application with the Pages Router and install the necessary `@upstash/redis` package for database interaction. SOURCE: https://upstash.com/docs/redis/quickstarts/nextjs-pages-router.mdx LANGUAGE: shell CODE: ``` npx create-next-app@latest cd my-app npm install @upstash/redis ``` ---------------------------------------- TITLE: Create Node.js Express Application with Upstash Redis Counter DESCRIPTION: This JavaScript code sets up an Express server that uses Upstash Redis to maintain a simple page view counter. It retrieves the current counter value, increments it, and displays it on the web page. It also includes a note about Node.js fetch API compatibility for older versions. SOURCE: https://upstash.com/docs/redis/quickstarts/koyeb.mdx LANGUAGE: javascript CODE: ``` // Note: if you are using Node.js version 17 or lower, // change the first line to the following: // const { Redis } = require ("@upstash/redis/with-fetch"); const { Redis } = require("@upstash/redis"); const express = require("express"); const app = express(); const redis = Redis.fromEnv(); app.get("/", async (req, res) => { const value = await redis.get("counter"); await redis.set("counter", parseInt(value || 0) + 1); res.send(`Counter: ${value || 0}`); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); ``` ---------------------------------------- TITLE: Add Email API Endpoint (addemail.js) DESCRIPTION: This API endpoint is responsible for collecting user emails and storing them in a Redis Set. It ensures that only unique and valid email addresses are added to the set. The endpoint includes a client-side email validation function to check the format of the provided email before attempting to store it. SOURCE: https://upstash.com/docs/redis/tutorials/roadmapvotingapp.mdx LANGUAGE: javascript CODE: ``` import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const email = body["email"]; redis.on("error", function (err) { throw err; }); if (email && validateEmail(email)) { await redis.sadd("emails", email); redis.quit(); res.json({ body: "success", }); } else { redis.quit(); res.json({ error: "Invalid email", }); } }; function validateEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } ``` ---------------------------------------- TITLE: Use Laravel Cache with Redis driver DESCRIPTION: Illustrates how to store and retrieve data using Laravel's `Cache` facade after Redis has been configured as the caching driver. This enables efficient and fast data caching within the application. SOURCE: https://upstash.com/docs/redis/quickstarts/laravel.mdx LANGUAGE: php CODE: ``` Cache::put('key', 'value', now()->addMinutes(10)); $value = Cache::get('key'); ``` ---------------------------------------- TITLE: Execute Atomic Redis Transaction with Upstash (TypeScript) DESCRIPTION: This snippet illustrates how to perform atomic transactions using the Upstash Redis client. Unlike pipelines, transactions guarantee that all commands within the `multi()` block are executed atomically, preventing interleaving by other commands. The `exec()` method commits the transaction and returns the results of the commands. SOURCE: https://upstash.com/docs/redis/sdks/ts/pipelining/pipeline-transaction.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ /* auth */ }); const p = redis.multi(); p.set("key", 2); p.incr("key"); // or inline: p.hset("key2", "field", { hello: "world" }).hvals("key2"); // execute the transaction const res = await p.exec<[Type1, Type2, Type3]>(); ``` ---------------------------------------- TITLE: Implement Django View with Upstash Redis Counter DESCRIPTION: This Python code defines a Django view function `index` that interacts with an Upstash Redis instance. It increments a counter in Redis on each request and displays the current count in an HTML response. SOURCE: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime.mdx LANGUAGE: python CODE: ``` from datetime import datetime from django.http import HttpResponse from upstash_redis import Redis redis = Redis.from_env() def index(request): count = redis.incr('counter') html = f'''

Counter: { count } ''' return HttpResponse(html) ``` ---------------------------------------- TITLE: Install FastAPI and Upstash Redis Client DESCRIPTION: Installs the necessary Python packages including FastAPI, the Upstash Redis client library, and Uvicorn, which is an ASGI server required to run the FastAPI application. SOURCE: https://upstash.com/docs/redis/tutorials/python_fastapi_caching.mdx LANGUAGE: shell CODE: ``` pip install fastapi upstash-redis uvicorn[standard] ``` ---------------------------------------- TITLE: Configure Celery Application with Upstash Redis DESCRIPTION: Initializes a Celery application, loading environment variables for Upstash Redis connection details. It constructs the Redis connection string with SSL and defines a simple `add` task, demonstrating how to set up Celery to use Upstash Redis as both broker and backend. SOURCE: https://upstash.com/docs/redis/integrations/celery.mdx LANGUAGE: python CODE: ``` import os from celery import Celery from dotenv import load_dotenv load_dotenv() # Configure Celery with Upstash Redis UPSTASH_REDIS_HOST = os.getenv("UPSTASH_REDIS_HOST") UPSTASH_REDIS_PORT = os.getenv("UPSTASH_REDIS_PORT") UPSTASH_REDIS_PASSWORD = os.getenv("UPSTASH_REDIS_PASSWORD") connection_link = f"rediss://:{UPSTASH_REDIS_PASSWORD}@{UPSTASH_REDIS_HOST}:{UPSTASH_REDIS_PORT}?ssl_cert_reqs=required" celery_app = Celery("tasks", broker=connection_link, backend=connection_link) @celery_app.task def add(x, y): return x + y ``` ---------------------------------------- TITLE: Create new Laravel project using CLI DESCRIPTION: Creates a new Laravel application named 'example-app' using the globally installed Laravel CLI. After creation, it navigates into the project directory, preparing for further development. SOURCE: https://upstash.com/docs/redis/quickstarts/laravel.mdx LANGUAGE: shell CODE: ``` laravel new example-app cd example-app ``` ---------------------------------------- TITLE: Deploy AWS CDK Application DESCRIPTION: These commands are used to deploy the AWS CDK application. `cdk synth` synthesizes the application into CloudFormation templates, `cdk bootstrap` prepares the AWS environment for CDK deployment (if not already done), and `cdk deploy` provisions the defined resources in your AWS account. SOURCE: https://upstash.com/docs/redis/quickstarts/aws-lambda.mdx LANGUAGE: shell CODE: ``` cdk synth cdk bootstrap cdk deploy ``` ---------------------------------------- TITLE: Initialize Azure Functions Project DESCRIPTION: Initializes a new Azure Functions project with TypeScript support using the Azure Functions Core Tools. This command sets up the basic project structure and configuration. SOURCE: https://upstash.com/docs/redis/quickstarts/azure-functions.mdx LANGUAGE: shell CODE: ``` func init --typescript ``` ---------------------------------------- TITLE: Python Example for Redis DEL Command DESCRIPTION: Demonstrates how to use the `delete` method with a Python Redis client to remove multiple keys and verify their successful removal. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/del.mdx LANGUAGE: python CODE: ``` redis.set("key1", "Hello") redis.set("key2", "World") redis.delete("key1", "key2") assert redis.get("key1") is None assert redis.get("key2") is None ``` ---------------------------------------- TITLE: Configure Serverless Service and Functions DESCRIPTION: Serverless Framework configuration in `serverless.yml`. It defines the AWS provider, Node.js runtime, passes Upstash Redis environment variables, and configures the `counter` function to be triggered by a GET request to the root path. SOURCE: https://upstash.com/docs/redis/tutorials/using_serverless_framework.mdx LANGUAGE: yaml CODE: ``` service: counter-serverless provider: name: aws runtime: nodejs20.x environment: UPSTASH_REDIS_REST_URL: ${env:UPSTASH_REDIS_REST_URL} UPSTASH_REDIS_REST_TOKEN: ${env:UPSTASH_REDIS_REST_TOKEN} functions: counter: handler: handler.counter events: - httpApi: path: / method: get ``` ---------------------------------------- TITLE: Implement Stale-While-Revalidate with Cache::flexible DESCRIPTION: Example of using Laravel's Cache::flexible method for stale-while-revalidate caching. It defines a "fresh" period (5 seconds) and a "stale" period (10 seconds), serving cached data immediately while asynchronously refreshing it during the stale period to balance performance and data freshness. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: php CODE: ``` $value = Cache::flexible('todos', [5, 10], function () { return Todo::all(); }); ``` ---------------------------------------- TITLE: Implement Google Cloud Function with Upstash Redis Counter DESCRIPTION: This JavaScript code defines a Google Cloud Function named 'counter' that increments a value in Upstash Redis. It initializes the Redis client using environment variables for the REST URL and token, then asynchronously increments a key named 'counter' and sends the result back as an HTTP response. SOURCE: https://upstash.com/docs/redis/quickstarts/google-cloud-functions.mdx LANGUAGE: javascript CODE: ``` const { Redis } = require("@upstash/redis"); const functions = require('@google-cloud/functions-framework'); const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }); functions.http('counter', async (req, res) => { const count = await redis.incr("counter"); res.send("Counter:" + count); }); ``` ---------------------------------------- TITLE: Implement Autocomplete Query API with ioredis DESCRIPTION: JavaScript code for 'handler.js' defining a serverless function to handle autocomplete queries. It connects to Redis, uses ZRANK and ZRANGE to find and filter terms based on a given prefix, and returns JSON results. SOURCE: https://upstash.com/docs/redis/tutorials/auto_complete_with_serverless_redis.mdx LANGUAGE: javascript CODE: ``` var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis(process.env.REDIS_URL); } const headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true }; module.exports.query = async (event, context, callback) => { if (!event.queryStringParameters || !event.queryStringParameters.term) { return { statusCode: 400, headers: headers, body: JSON.stringify({ message: "Invalid parameters. Term needed as query param." }) }; } let term = event.queryStringParameters.term.toUpperCase(); let res = []; let rank = await client.zrank("terms", term); if (rank != null) { let temp = await client.zrange("terms", rank, rank + 100); for (const el of temp) { if (!el.startsWith(term)) { break; } if (el.endsWith("*")) { res.push(el.substring(0, el.length - 1)); } } } return { statusCode: 200, headers: headers, body: JSON.stringify({ message": "Query:" + event.queryStringParameters.term, result": res }) }; }; ``` ---------------------------------------- TITLE: Python Script to Test FastAPI Session Endpoints DESCRIPTION: A Python script designed to test the FastAPI application's session management endpoints. It simulates user login, profile access, and logout requests, demonstrating how to interact with the API and handle session cookies. SOURCE: https://upstash.com/docs/redis/tutorials/python_session.mdx LANGUAGE: Python CODE: ``` import requests base_url = "http://127.0.0.1:8000" # Test login response = requests.post(f"{base_url}/login/", json={"username": "abdullah"}) print("Login Response:", response.json()) # In the browser, you don't need to set cookies manually. The browser will handle it automatically. session_cookie = response.cookies.get("session_id") # Test profile profile_response = requests.get(f"{base_url}/profile/", cookies={"session_id": session_cookie}) print("Access Profile Response:", profile_response.json()) # Test logout logout_response = requests.post(f"{base_url}/logout/", cookies={"session_id": session_cookie}) print("Logout Response:", logout_response.json()) # Test profile after logout profile_after_logout_response = requests.get(f"{base_url}/profile/", cookies={"session_id": session_cookie}) print("Access Profile After Logout Response:", profile_after_logout_response.text) ``` ---------------------------------------- TITLE: Load Lua Script using Upstash Redis Client (TypeScript) DESCRIPTION: This example demonstrates how to use the Upstash Redis client in TypeScript to load a Lua script into the Redis script cache. It shows the `scriptLoad` method call and how to define an inline Lua script. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/scripts/script_load.mdx LANGUAGE: TypeScript CODE: ``` const script = ` local value = redis.call('GET', KEYS[1]) return value `; const sha1 = await redis.scriptLoad(script); ``` ---------------------------------------- TITLE: Implement Flask SocketIO Server with Upstash Redis DESCRIPTION: This Python code sets up a Flask application with Flask-SocketIO for real-time communication. It configures the SocketIO instance to use Upstash Redis as a message queue, handling client connections, disconnections, and broadcasting chat messages. It also demonstrates secure connection to Redis using the `rediss://` protocol. SOURCE: https://upstash.com/docs/redis/tutorials/python_realtime_chat.mdx LANGUAGE: python CODE: ``` from flask import Flask, render_template from flask_socketio import SocketIO import os # Initialize Flask app app = Flask(__name__) app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", os.urandom(24)) # Set up Redis URL with TLS redis_password = os.getenv('UPSTASH_REDIS_PASSWORD') redis_host = os.getenv('UPSTASH_REDIS_HOST') redis_port = int(os.getenv('UPSTASH_REDIS_PORT', 6379)) redis_url = f"rediss://:{redis_password}@{redis_host}:{redis_port}" # Initialize SocketIO with Redis message queue socketio = SocketIO(app, message_queue=redis_url, cors_allowed_origins="*") # WebSocket handlers @socketio.on("connect") def handle_connect(): print("Client connected.") @socketio.on("disconnect") def handle_disconnect(): print("Client disconnected.") @socketio.on("message") def handle_message(data): """Handle incoming chat messages.""" print(f"Message received: {data}") # Broadcast the message to all connected clients except the sender socketio.emit("message", data, include_self=False) # Serve the chat HTML page @app.route("/") def index(): return render_template("chat.html") # Render the chat interface template if __name__ == "__main__": socketio.run(app, debug=True, host="0.0.0.0", port=8000) ``` ---------------------------------------- TITLE: Integrate Serverless Redis HTTP (SRH) into GitHub Actions CI DESCRIPTION: This GitHub Actions workflow demonstrates how to set up SRH and a Redis server as services within a job. It allows running tests against the SRH proxy, simulating an Upstash Redis environment for CI/CD pipelines without external dependencies, ensuring compatibility and reducing test setup overhead. SOURCE: https://upstash.com/docs/redis/sdks/ts/developing.mdx LANGUAGE: yml CODE: ``` name: Test @upstash/redis compatibility on: push: workflow_dispatch: env: SRH_TOKEN: example_token jobs: container-job: runs-on: ubuntu-latest container: denoland/deno services: redis: image: redis/redis-stack-server:6.2.6-v6 # 6.2 is the Upstash compatible Redis version srh: image: hiett/serverless-redis-http:latest env: SRH_MODE: env # We are using env mode because we are only connecting to one server. SRH_TOKEN: ${{ env.SRH_TOKEN }} SRH_CONNECTION_STRING: redis://redis:6379 steps: # You can place your normal testing steps here. In this example, we are running SRH against the upstash/upstash-redis test suite. - name: Checkout code uses: actions/checkout@v3 with: repository: upstash/upstash-redis - name: Run @upstash/redis Test Suite run: deno test -A ./pkg env: UPSTASH_REDIS_REST_URL: http://srh:80 UPSTASH_REDIS_REST_TOKEN: ${{ env.SRH_TOKEN }} ``` ---------------------------------------- TITLE: Generate Upstash Developer API Key (SPA) DESCRIPTION: Demonstrates how a Single Page Application (SPA) can generate a Developer API Key after a successful OAuth 2.0 flow. This involves making a POST request to the Upstash API with a JWT token for authorization and specifying a name for the new API key. SOURCE: https://upstash.com/docs/redis/help/integration.mdx LANGUAGE: bash CODE: ``` curl -XPOST https://api.upstash.com/apikey \ -H "Authorization: Bearer JWT_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "APPNAME_API_KEY_TIMESTAMP" }' ``` ---------------------------------------- TITLE: Next.js Pages Router Home Page with Upstash Redis Counter DESCRIPTION: TypeScript/TSX code for the `/pages/index.tsx` file. This example demonstrates how to use `getServerSideProps` to fetch and increment a counter value from Upstash Redis, displaying it on the Next.js home page. SOURCE: https://upstash.com/docs/redis/quickstarts/nextjs-pages-router.mdx LANGUAGE: tsx CODE: ``` import type { InferGetServerSidePropsType, GetServerSideProps } from 'next' import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export const getServerSideProps = (async () => { const count = await redis.incr("counter"); return { props: { count } } }) satisfies GetServerSideProps<{ count: number }> export default function Home({ count, }: InferGetServerSidePropsType) { return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: Implement Sliding Window Ratelimiting with Upstash Redis DESCRIPTION: Shows how to create a ratelimiter using the sliding window algorithm, allowing 10 requests per 10 seconds. Examples are provided for regional and multi-regional Upstash Redis configurations, with a warning about multi-regional usage. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/algorithms.mdx LANGUAGE: ts CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), }); ``` LANGUAGE: ts CODE: ``` const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), }); ``` ---------------------------------------- TITLE: Implement Redis Pipelining in Python DESCRIPTION: This snippet shows how to use Redis pipelining with the `upstash-redis` client to batch multiple commands. Pipelining reduces roundtrips to the server, improving performance. Commands are added to the pipeline and then executed using `.exec()`, returning a list of results in order. SOURCE: https://upstash.com/docs/redis/sdks/py/features.mdx LANGUAGE: python CODE: ``` pipeline = redis.pipeline() pipeline.set("foo", 1) pipeline.incr("foo") pipeline.get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ``` ---------------------------------------- TITLE: Implement Serverless Page View Counter Function DESCRIPTION: Defines the AWS Lambda handler function in Python. It initializes a Redis client from environment variables, increments a 'counter' key in Redis, and returns the updated count in a JSON response. SOURCE: https://upstash.com/docs/redis/tutorials/pythonapi.mdx LANGUAGE: python CODE: ``` from upstash_redis import Redis redis = Redis.from_env() def handler(event, context): count = redis.incr('counter') return { 'statusCode': 200, 'body': f'Counter: {count}' } ``` ---------------------------------------- TITLE: Configure Upstash Redis Credentials in wrangler.toml DESCRIPTION: This YAML snippet illustrates how to manually configure the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` as environment variables within your Cloudflare Worker's `wrangler.toml` file. These variables are crucial for the Worker to connect to your Upstash Redis database. SOURCE: https://upstash.com/docs/redis/quickstarts/cloudflareworkers.mdx LANGUAGE: yaml CODE: ``` [vars] UPSTASH_REDIS_REST_URL="REPLACE_HERE" UPSTASH_REDIS_REST_TOKEN="REPLACE_HERE" ``` ---------------------------------------- TITLE: Node.js Server with Redis Counter DESCRIPTION: A Node.js HTTP server implementation that uses the 'ioredis' library to connect to an Upstash Redis instance. It increments a 'counter' key in Redis on each page view and displays the current count as the response. The Redis connection URL is expected from the environment variable REDIS_URL. SOURCE: https://upstash.com/docs/redis/tutorials/aws_app_runner_with_redis.mdx LANGUAGE: JavaScript CODE: ``` var Redis = require("ioredis"); const http = require("http"); if (typeof client === "undefined") { var client = new Redis(process.env.REDIS_URL); } const requestListener = async function (req, res) { if (req.url !== "/favicon.ico") { let count = await client.incr("counter"); res.writeHead(200); res.end("Page view:" + count); } }; const server = http.createServer(requestListener); server.listen(8080); ``` ---------------------------------------- TITLE: Client-side Message Sending and Input Handling DESCRIPTION: This JavaScript snippet handles sending messages from the client to the server via a WebSocket connection and allows users to send messages by pressing the Enter key in the input field. It updates the UI with sent messages and clears the input field. SOURCE: https://upstash.com/docs/redis/tutorials/python_realtime_chat.mdx LANGUAGE: JavaScript CODE: ``` addMessage(`You: ${message}`, "sent"); socket.emit("message", { user: username, message }); messageInput.value = ""; ``` LANGUAGE: JavaScript CODE: ``` messageInput.addEventListener("keypress", (e) => { if (e.key === "Enter") { sendButton.click(); } }); ``` ---------------------------------------- TITLE: Next.js API Route with Upstash Redis Counter DESCRIPTION: Implements a Next.js API route (`/pages/api/hello.ts`) that demonstrates basic interaction with Upstash Redis. It increments a counter on each request and returns the current count as a JSON response. SOURCE: https://upstash.com/docs/redis/quickstarts/vercel-functions-pages-router.mdx LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; import type { NextApiRequest, NextApiResponse } from "next"; const redis = Redis.fromEnv(); export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const count = await redis.incr("counter"); res.status(200).json({ count }); } ``` ---------------------------------------- TITLE: Connect to Upstash Redis using upstash-redis (TypeScript) DESCRIPTION: This example demonstrates how to connect to an Upstash Redis database using the `@upstash/redis` library in TypeScript. It initializes a Redis client with the REST URL and token, then performs a basic `get` operation to retrieve data. SOURCE: https://upstash.com/docs/redis/howto/connectclient.mdx LANGUAGE: typescript CODE: ``` import { Redis } from '@upstash/redis'; const redis = new Redis({ url: 'UPSTASH_REDIS_REST_URL', token: 'UPSTASH_REDIS_REST_TOKEN' }); (async () => { try { const data = await redis.get('key'); console.log(data); } catch (error) { console.error(error); } })(); ``` ---------------------------------------- TITLE: Install Upstash Redis Package DESCRIPTION: These snippets provide instructions for installing the `@upstash/redis` package using popular Node.js package managers: npm, yarn, and pnpm. Choose the command that matches your project's package manager. SOURCE: https://upstash.com/docs/redis/sdks/ts/getstarted.mdx LANGUAGE: bash CODE: ``` npm install @upstash/redis ``` LANGUAGE: bash CODE: ``` yarn add @upstash/redis ``` LANGUAGE: bash CODE: ``` pnpm add @upstash/redis ``` ---------------------------------------- TITLE: Project Setup: Create SST Next.js Application DESCRIPTION: Initializes a new SST project using the standard Next.js template, navigates into the newly created project directory, and installs all required Node.js dependencies. SOURCE: https://upstash.com/docs/redis/quickstarts/sst-v2.mdx LANGUAGE: shell CODE: ``` npx create-sst@latest --template standard/nextjs cd my-sst-app npm install ``` ---------------------------------------- TITLE: Apply Custom Rate Decrements with Upstash Ratelimit DESCRIPTION: This example illustrates how to subtract a custom value from the available rate limit instead of the default '1'. This is particularly useful for scenarios where operations consume varying amounts of 'rate', such as processing user input in batches, allowing more granular control over rate limiting. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/features.mdx LANGUAGE: ts CODE: ``` const { success } = await ratelimit.limit("identifier", { rate: batchSize }); ``` ---------------------------------------- TITLE: Install FastAPI and Upstash Redis Libraries DESCRIPTION: Installs the necessary Python packages, FastAPI for web framework and upstash-redis for Redis client, using the pip package manager. SOURCE: https://upstash.com/docs/redis/quickstarts/fastapi.mdx LANGUAGE: shell CODE: ``` pip install fastapi pip install upstash-redis ``` ---------------------------------------- TITLE: Configure Ephemeral In-Memory Cache for Ratelimit DESCRIPTION: This snippet demonstrates how to configure an ephemeral in-memory cache using a `Map` for the `Ratelimit` instance. The cache helps reduce Redis calls for blocked identifiers, especially in serverless environments when the instance is kept 'hot'. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/features.mdx LANGUAGE: TypeScript CODE: ``` const cache = new Map(); // must be outside of your serverless function handler // ... const ratelimit = new Ratelimit({ // ... ephemeralCache: cache, }); ``` ---------------------------------------- TITLE: TypeScript: Execute EVALSHA_RO Command DESCRIPTION: Example demonstrating how to use the `evalshaRo` method with the Upstash Redis client in TypeScript to execute a cached read-only Lua script by its SHA1 hash. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/scripts/evalsha_ro.mdx LANGUAGE: ts CODE: ``` const result = await redis.evalshaRo("fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", [], ["hello"]); console.log(result) // "hello" ``` ---------------------------------------- TITLE: Implement Google Cloud Function Counter with Upstash Redis DESCRIPTION: This JavaScript code defines a Google Cloud Function named 'counter' that increments a Redis counter using the @upstash/redis client. It retrieves Redis connection details (URL and token) from environment variables and returns the current count as a response. SOURCE: https://upstash.com/docs/redis/tutorials/using_google_cloud_functions.mdx LANGUAGE: javascript CODE: ``` const { Redis } = require("@upstash/redis"); const functions = require('@google-cloud/functions-framework'); const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }); functions.http('counter', async (req, res) => { const count = await redis.incr("counter"); res.send("Counter:" + count); }); ``` ---------------------------------------- TITLE: Apply Multiple Rate Limits with Upstash Ratelimit DESCRIPTION: This example illustrates how to implement different rate-limiting policies for various user groups, such as free versus paid users. It shows the creation of multiple `Ratelimit` instances, each configured with distinct limits and prefixes, allowing for flexible, tiered access control. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-py/features.mdx LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, SlidingWindow from upstash_redis import Redis class MultiRL: def __init__(self) -> None: redis = Redis.from_env() self.free = Ratelimit( redis=redis, limiter=SlidingWindow(max_requests=10, window=10), prefix="ratelimit:free", ) self.paid = Ratelimit( redis=redis, limiter=SlidingWindow(max_requests=60, window=10), prefix="ratelimit:paid", ) # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = MultiRL() ratelimit.free.limit("userIP") ratelimit.paid.limit("userIP") ``` ---------------------------------------- TITLE: Optimize Auto-Pipelining with Promise.all for Multiple Commands DESCRIPTION: This snippet highlights the importance of using `Promise.all` when executing multiple Redis commands to fully leverage auto-pipelining. Awaiting each command individually triggers separate pipeline calls, while `Promise.all` ensures a single, efficient `PIPELINE` command for all grouped operations. SOURCE: https://upstash.com/docs/redis/sdks/ts/pipelining/auto-pipeline.mdx LANGUAGE: TypeScript CODE: ``` const foo = await redis.get("foo") // makes a PIPELINE call const bar = await redis.get("bar") // makes another PIPELINE call ``` LANGUAGE: TypeScript CODE: ``` // makes a single PIPELINE call: const [ foo, bar ] = await Promise.all([ redis.get("foo"), redis.get("bar") ]) ``` ---------------------------------------- TITLE: Monitor Upstash Redis Commands with ioredis DESCRIPTION: This TypeScript example demonstrates how to use the `ioredis` client to connect to an Upstash Redis database and set up a real-time monitor. It listens for the 'monitor' event, logging details of each executed command, including timestamp, arguments, source, and database, to the console. SOURCE: https://upstash.com/docs/redis/howto/monitoryourusage.mdx LANGUAGE: ts CODE: ``` const monitor = await redis.monitor() monitor.on("monitor", (time, args, source, database) => { console.log(time, args, source, database) }) ``` ---------------------------------------- TITLE: Python Example for HGET Usage DESCRIPTION: Demonstrates how to use the HGET command in Python with a Redis client. This example shows setting a hash field and then retrieving both an existing field and a non-existing field, asserting the expected outcomes for each case. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/hash/hget.mdx LANGUAGE: python CODE: ``` redis.hset("myhash", "field1", "Hello") assert redis.hget("myhash", "field1") == "Hello" assert redis.hget("myhash", "field2") is None ``` ---------------------------------------- TITLE: Initialize Ratelimit Client for Auto IP Deny List DESCRIPTION: Configures the Ratelimit client to enable automatic IP blocking. By setting `enableProtection` to `true`, the SDK will automatically leverage open-source IP deny lists (like those aggregated by `ipsum`) to block malicious IP addresses when provided in the `limit` method. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/traffic-protection.mdx LANGUAGE: ts CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), enableProtection: true, }); ``` ---------------------------------------- TITLE: Install and Import Upstash Ratelimit DESCRIPTION: Instructions for installing the `@upstash/ratelimit` package using npm for Node.js projects and importing the `Ratelimit` class for Deno environments. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: bash CODE: ``` npm install @upstash/ratelimit ``` LANGUAGE: ts CODE: ``` import { Ratelimit } from "https://cdn.skypack.dev/@upstash/ratelimit@latest"; ``` ---------------------------------------- TITLE: Mapping Redis Commands to Upstash REST API URLs DESCRIPTION: Provides several examples demonstrating how various Redis commands (SET, GET, MGET, HGET, ZADD) are translated into corresponding URL paths for the Upstash REST API, following the Redis Protocol convention. SOURCE: https://upstash.com/docs/redis/features/restapi.mdx LANGUAGE: shell CODE: ``` - `SET foo bar` -> `REST_URL/set/foo/bar` - `SET foo bar EX 100` -> `REST_URL/set/foo/bar/EX/100` - `GET foo` -> `REST_URL/get/foo` - `MGET foo1 foo2 foo3` -> `REST_URL/mget/foo1/foo2/foo3` - `HGET employee:23381 salary` -> `REST_URL/hget/employee:23381/salary` - `ZADD teams 100 team-x 90 team-y` -> `REST_URL/zadd/teams/100/team-x/90/team-y` ``` ---------------------------------------- TITLE: TypeScript Examples for JSON.SET DESCRIPTION: Illustrates various ways to use the `redis.json.set` method in TypeScript, including basic usage and conditional setting with `NX` (set if not exists) and `XX` (set if exists) options. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/json/set.mdx LANGUAGE: ts CODE: ``` Set the JSON value at path in key. redis.json.set(key, "$.path", value); ``` LANGUAGE: ts CODE: ``` const value = ... redis.json.set(key, "$.path", value, { nx:true }); ``` LANGUAGE: ts CODE: ``` const value = ... redis.json.set(key, "$.path", value, { xx:true }); ``` ---------------------------------------- TITLE: Configure Sidekiq and Implement Email Service Worker DESCRIPTION: Illustrates how to configure Sidekiq client and server to connect to Upstash Redis using an environment variable. It defines an 'EmailService' Sidekiq worker and provides helper functions for asynchronously sending, updating, and clearing email-related jobs with varying delays based on email type. SOURCE: https://upstash.com/docs/redis/integrations/sidekiq.mdx LANGUAGE: ruby CODE: ``` require "sidekiq" require "sidekiq/api" connection_url = ENV['UPSTASH_REDIS_LINK'] Sidekiq.configure_client do |config| config.redis = {url: connection_url} end Sidekiq.configure_server do |config| config.redis = {url: connection_url} end class EmailService include Sidekiq::Worker def perform(id, type) # Logic goes here. Let's assume sending email by printing to console. puts "Emailed to: " + id + ": " + "'Congrats on " + type + " plan.'" end end def updateEmail(id, newType) jobFound = false a = Sidekiq::ScheduledSet.new a.each do |job| if job.args[0] == id job.delete jobFound = true end end if jobFound EmailService.perform_async(id, ("starting using our service and upgrading it to " + newType)) else EmailService.perform_async(id, ("upgrading to " + newType)) end end def sendEmail(id, type) case type when "free" # if free, delay for 10 seconds. EmailService.perform_in("10", id, "free") when "paid" # if paid, delay for 5 seconds. EmailService.perform_in("5", id, "paid") when "enterprise" # if enterprise, immediately queue. EmailService.perform_async(id, "enterprise") when "enterprise10k" EmailService.perform_async(id, "enterprise10k") else puts "Only plans are: `free`, `paid` and `enterprise`" end end def clearSchedules() Sidekiq::ScheduledSet.new.clear Sidekiq::Queue.new.clear end ``` ---------------------------------------- TITLE: Handle Asynchronous Auto IP Deny List Updates DESCRIPTION: Demonstrates how to properly handle the `pending` field returned by `ratelimit.limit` when using the Auto IP Deny List feature. This is crucial for ensuring that asynchronous updates to the IP deny list (which occur daily) complete successfully in the background, without blocking the user's request. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/traffic-protection.mdx LANGUAGE: ts CODE: ``` const { success, pending } = await ratelimit.limit( content, {ip: "ip-address"} ); await pending; ``` ---------------------------------------- TITLE: Ensuring Ratelimit Operations Complete in Serverless Environments DESCRIPTION: This snippet demonstrates how to use the `pending` promise returned by `ratelimit.limit()` in conjunction with `context.waitUntil` to ensure that asynchronous background operations (like multi-region synchronization or analytics sending) initiated by the ratelimiter complete before the serverless function's runtime ends. This is crucial for reliable rate limiting in environments like Cloudflare Workers or Vercel Edge. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: ts CODE: ``` const { pending } = await ratelimit.limit("id"); context.waitUntil(pending); ``` ---------------------------------------- TITLE: Python Example for Iterating Redis SSCAN DESCRIPTION: This Python code snippet demonstrates how to use the Redis SSCAN command to retrieve all members from a set. It shows the iterative process of calling SSCAN with a cursor until all members have been fetched. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/set/sscan.mdx LANGUAGE: python CODE: ``` # Get all members of a set. cursor = 0 results = set() while True: cursor, keys = redis.sscan("myset", cursor, match="*") results.extend(keys) if cursor == 0: break ``` ---------------------------------------- TITLE: Initialize Token Bucket Ratelimit with Upstash Redis DESCRIPTION: Demonstrates the setup of a token bucket ratelimiter using `upstash_ratelimit` and `upstash_redis`. It defines the maximum number of tokens, the refill rate, and the interval for token replenishment. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-py/algorithms.mdx LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, TokenBucket from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=TokenBucket(max_tokens=10, refill_rate=5, interval=10), ) ``` ---------------------------------------- TITLE: Implement AWS Lambda Counter Function with Upstash Redis DESCRIPTION: Defines the Python Lambda handler function (`lambda_handler`) that connects to Upstash Redis using environment variables, increments a counter, and returns the current count. This function demonstrates basic interaction with Redis within a serverless context, showcasing how to use `upstash-redis`. SOURCE: https://upstash.com/docs/redis/tutorials/using_aws_sam.mdx LANGUAGE: python CODE: ``` from upstash_redis import Redis redis = Redis.from_env() def lambda_handler(event, context): count = redis.incr('counter') return { 'statusCode': 200, 'body': f'Counter: {count}' } ``` ---------------------------------------- TITLE: TypeScript Example for EVALSHA Command DESCRIPTION: Demonstrates how to use the EVALSHA command in TypeScript with the redis client, showing a basic execution and logging the result. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/scripts/evalsha.mdx LANGUAGE: ts CODE: ``` const result = await redis.evalsha("fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", [], ["hello"]); console.log(result) // "hello" ``` ---------------------------------------- TITLE: Orchestrate Weather Data Fetching with Caching (Elixir) DESCRIPTION: Defines a private Elixir function `fetch_weather` responsible for coordinating weather data retrieval. It prioritizes fetching from a local cache and, if unsuccessful, falls back to making a request to an external weather API. The function handles various outcomes, returning either successful data or an error. SOURCE: https://upstash.com/docs/redis/quickstarts/elixir.mdx LANGUAGE: Elixir CODE: ``` defp fetch_weather(location) do location = String.replace(location, " ", "%20") case fetch_weather_from_cache(location) do {:ok, cached_weather} -> {:ok, cached_weather} {:error, :not_found} -> fetch_weather_from_api(location) {:error, reason} -> {:error, reason} end end ``` ---------------------------------------- TITLE: Implement Azure Function with Upstash Redis Counter DESCRIPTION: TypeScript code for an Azure Function that increments a counter in Upstash Redis on each HTTP request and returns the current count. It initializes the Redis client using environment variables for URL and token, ensuring secure connection. SOURCE: https://upstash.com/docs/redis/quickstarts/azure-functions.mdx LANGUAGE: typescript CODE: ``` import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions"; import { Redis } from "@upstash/redis"; const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }); export async function CounterFunction(request: HttpRequest, context: InvocationContext): Promise { const count = await redis.incr("counter"); return { status: 200, body: `Counter: ${count}` }; }; app.http('CounterFunction', { methods: ['GET', 'POST'], authLevel: 'anonymous', handler: CounterFunction }); ``` ---------------------------------------- TITLE: Fetch Weather Data from External API and Cache (Elixir) DESCRIPTION: Defines `fetch_weather_from_api`, which makes an HTTP GET request to the WeatherAPI using an environment variable for the API key. Upon a successful 200 OK response, it decodes the JSON body, extracts relevant weather details, and then caches this information in Redis using `cache_weather_response` before returning the processed data. SOURCE: https://upstash.com/docs/redis/quickstarts/elixir.mdx LANGUAGE: Elixir CODE: ``` defp fetch_weather_from_api(location) do weather_api_key = System.get_env("WEATHER_API_KEY") url = "http://api.weatherapi.com/v1/current.json?key=#{weather_api_key}&q=#{location}&aqi=no" case HTTPoison.get(url) do {:ok, %{status_code: 200, body: body}} -> weather_info = body |> Jason.decode!() |> get_weather_info() # Cache the weather response in Redis for 8 hours cache_weather_response(location, Jason.encode!(weather_info)) {:ok, weather_info} {:ok, %{status_code: status_code, body: body}} -> {:error, "#{body} (#{status_code})"} {:error, _reason} -> {:error, "Failed to fetch weather data."} end end ``` ---------------------------------------- TITLE: Handle Pending Promises in Multi-Region Ratelimit DESCRIPTION: This snippet addresses the specific requirement for handling asynchronous synchronization in serverless environments like Cloudflare Workers or Vercel Edge Functions. It shows how to use `context.waitUntil(pending)` to ensure that background replication tasks initiated by `MultiRegionRatelimit` complete before the function execution context is terminated, preventing data inconsistencies. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/features.mdx LANGUAGE: ts CODE: ``` const { pending } = await ratelimit.limit("id"); context.waitUntil(pending); ``` ---------------------------------------- TITLE: Invoke and Retrieve Result of Celery Task DESCRIPTION: Demonstrates how to call a Celery task asynchronously using `delay()` and retrieve its result using `get()`. It shows the initial pending state and the final computed output of the `add` task. SOURCE: https://upstash.com/docs/redis/integrations/celery.mdx LANGUAGE: python CODE: ``` from tasks import add result = add.delay(4, 6) print(f"Task state: {result.state}") # Outputs 'PENDING' initially # Wait for the result output = result.get(timeout=10) print(f"Task result: {output}") # Outputs '10' ``` ---------------------------------------- TITLE: Implement Serverless Histogram API Logic (handler.js) DESCRIPTION: Node.js code for `handler.js` containing the core logic for the `get` and `record` Lambda functions. It handles API requests, interacts with Redis using `ioredis` to store and retrieve data, and uses `hdr-histogram-js` to build histograms from the retrieved values. A helper function `fixUrl` is included to correct Redis URL formats. SOURCE: https://upstash.com/docs/redis/tutorials/histogram.mdx LANGUAGE: javascript CODE: ``` const hdr = require("hdr-histogram-js"); const Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis(fixUrl(process.env.REDIS_URL)); } const headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true, }; const SIZE = 10000; module.exports.get = async (event) => { if (!event.queryStringParameters || !event.queryStringParameters.name) { return { statusCode: 400, headers: headers, body: JSON.stringify({ message: "Invalid parameters. Name is needed.", }), }; } const name = event.queryStringParameters.name; const data = await client.lrange(name, 0, SIZE); const histogram = hdr.build(); data.forEach((item) => { histogram.recordValue(item); }); return { statusCode: 200, body: JSON.stringify({ histogram: histogram, }), }; }; module.exports.record = async (event) => { let body = JSON.parse(event.body); if (!body || !body.name || !body.values) { return { statusCode: 400, headers: headers, body: JSON.stringify({ message: "Invalid parameters. Name and values are needed.", }), }; } const name = body.name; const values = body.values; await client.lpush(name, values); return { statusCode: 200, body: JSON.stringify({ message: "Success", name: name, }), }; }; function fixUrl(url) { if (!url) { return ""; } if (url.startsWith("redis://") && !url.startsWith("redis://:")) { return url.replace("redis://", "redis://:"); } if (url.startsWith("rediss://") && !url.startsWith("rediss://:")) { return url.replace("rediss://", "rediss://:"); } return url; } ``` ---------------------------------------- TITLE: Scan a Redis Set with SSCAN in TypeScript DESCRIPTION: This example demonstrates how to use the `SSCAN` command with Upstash Redis in TypeScript to scan a set, filter members using a glob pattern, and retrieve results. It shows initial setup with `sadd`, then calling `sscan` with a cursor and a `match` option, and finally logging the new cursor and the retrieved fields. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/set/sscan.mdx LANGUAGE: TypeScript CODE: ``` await redis.sadd("key", "a", "ab","b", "c"); const [newCursor, fields] = await redis.sscan("key", 0, { match: "a*"}); console.log(newCursor); // likely `0` since this is a very small set console.log(fields); // ["a", "ab"] ``` ---------------------------------------- TITLE: Implement Flask Application with Redis Counter Logic DESCRIPTION: This Python script (`app.py`) defines a Flask web application. It initializes a connection to Upstash Redis using environment variables, creates a root route (`/`) that increments a 'counter' key in Redis on each visit, and displays the updated count to the user. SOURCE: https://upstash.com/docs/redis/quickstarts/flask.mdx LANGUAGE: python CODE: ``` from flask import Flask from upstash_redis import Redis app = Flask(__name__) redis = Redis.from_env() @app.route('/') def index(): count = redis.incr('counter') return f'Page visited {count} times.' if __name__ == '__main__': app.run(debug=True) ``` ---------------------------------------- TITLE: Load and Execute Lua Script with Python DESCRIPTION: This Python example demonstrates how to use the `script_load` method to load a Lua script into Redis and then execute it using `evalsha`, asserting the correct return value. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/scripts/script_load.mdx LANGUAGE: python CODE: ``` sha1 = redis.script_load("return 1") assert redis.evalsha(sha1) == 1 ``` ---------------------------------------- TITLE: Add Start Script to package.json DESCRIPTION: This JSON snippet shows how to add a `start` script to the `package.json` file. This script allows the application to be easily started using `npm start`, which executes the `index.js` file with Node.js. SOURCE: https://upstash.com/docs/redis/tutorials/cloud_run_sessions.mdx LANGUAGE: json CODE: ``` "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index" } ``` ---------------------------------------- TITLE: Deploy Serverless Service to AWS DESCRIPTION: Command to deploy the configured Serverless service and its functions to AWS Lambda, making them accessible via the defined HTTP API endpoint. SOURCE: https://upstash.com/docs/redis/tutorials/using_serverless_framework.mdx LANGUAGE: shell CODE: ``` serverless deploy ``` ---------------------------------------- TITLE: Configure Serverless Project for Histogram API DESCRIPTION: Serverless configuration (`serverless.yml`) defining the AWS provider, Node.js runtime, and environment variables, specifically `REDIS_URL`. It also sets up two Lambda functions, `record` and `get`, mapping them to HTTP API endpoints with CORS enabled. SOURCE: https://upstash.com/docs/redis/tutorials/histogram.mdx LANGUAGE: yaml CODE: ``` service: histogram-api frameworkVersion: "2" provider: name: aws runtime: nodejs12.x lambdaHashingVersion: 20201221 environment: REDIS_URL: REPLACE_YOUR_URL_HERE functions: record: handler: handler.record events: - httpApi: path: /record method: post cors: true get: handler: handler.get events: - httpApi: path: /get method: get cors: true ``` ---------------------------------------- TITLE: Redis Transaction Commands DESCRIPTION: Documents the Transaction commands supported by Upstash Redis, enabling atomic execution of a group of commands. These commands allow queuing commands, executing transactions, and managing watches. SOURCE: https://upstash.com/docs/redis/overall/rediscompatibility.mdx LANGUAGE: APIDOC CODE: ``` DISCARD EXEC MULTI UNWATCH WATCH ``` ---------------------------------------- TITLE: SST Configuration: Bind Upstash Redis Secrets to Next.js Site DESCRIPTION: Configures the SST stack to bind the previously set Upstash Redis secrets (`UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN`) to the Next.js site construct. This makes the secrets accessible within your Next.js application. SOURCE: https://upstash.com/docs/redis/quickstarts/sst-v2.mdx LANGUAGE: ts CODE: ``` import { Config, StackContext, NextjsSite } from "sst/constructs"; export function Default({ stack }: StackContext) { const UPSTASH_REDIS_REST_URL = new Config.Secret(stack, "UPSTASH_REDIS_REST_URL"); const UPSTASH_REDIS_REST_TOKEN = new Config.Secret(stack, "UPSTASH_REDIS_REST_TOKEN"); const site = new NextjsSite(stack, "site", { bind: [UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN], path: "packages/web", }); stack.addOutputs({ SiteUrl: site.url, }); } ``` ---------------------------------------- TITLE: Fastly Compute@Edge JavaScript Application DESCRIPTION: This JavaScript code defines a Fastly Compute@Edge function. It initializes an Upstash Redis client using the provided URL and token, increments a 'count' key in Redis, and returns the current view count as a response. This demonstrates the core logic for integrating Redis within the Fastly environment. SOURCE: https://upstash.com/docs/redis/quickstarts/fastlycompute.mdx LANGUAGE: javascript CODE: ``` import { Redis } from "@upstash/redis/fastly"; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN", backend: "upstash", }); const data = await redis.incr("count"); return new Response("View Count:" + data, { status: 200 }); } ``` ---------------------------------------- TITLE: Retrieve Multiple Keys with MGET in Python DESCRIPTION: Demonstrates how to use the MGET command in Python to retrieve multiple keys from Redis. This example shows setting two keys and then asserting that MGET correctly returns their corresponding values in a list. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/mget.mdx LANGUAGE: Python CODE: ``` redis.set("key1", "value1") redis.set("key2", "value2") assert redis.mget("key1", "key2") == ["value1", "value2"] ``` ---------------------------------------- TITLE: Configure Cloudflare Worker `wrangler.toml` DESCRIPTION: Initial configuration file for a Cloudflare Workers project, including project name, type, account ID, and environment variables for the Upstash Redis token. SOURCE: https://upstash.com/docs/redis/tutorials/edge_leaderboard.mdx LANGUAGE: toml CODE: ``` name = "edge-leaderboard" type = "javascript" account_id = "REPLACE_YOUR_ACCOUNT_ID" workers_dev = true route = "" zone_id = "" [vars] TOKEN = "REPLACE_YOUR_UPSTASH_REST_TOKEN" ``` ---------------------------------------- TITLE: Perform a simple ZINTERSTORE operation in TypeScript DESCRIPTION: Demonstrates how to use `redis.zinterstore` to compute the intersection of two sorted sets without additional options, storing the result in a new key. It initializes two sorted sets and then performs the intersection. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/zset/zinterstore.mdx LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zinterstore("destination", 2, ["key1", "key2"]); console.log(res) // 1 ``` ---------------------------------------- TITLE: Python RPOP Examples DESCRIPTION: Examples demonstrating the usage of the RPOP command in Python, showing how to pop single or multiple elements from a Redis list. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/list/rpop.mdx LANGUAGE: Python CODE: ``` redis.rpush("mylist", "one", "two", "three") assert redis.rpop("mylist") == "three" ``` LANGUAGE: Python CODE: ``` redis.rpush("mylist", "one", "two", "three") assert redis.rpop("mylist", 2) == ["three", "two"] ``` ---------------------------------------- TITLE: TypeScript Example for INCRBY DESCRIPTION: An example demonstrating how to use the INCRBY command with a TypeScript Redis client, showing a set operation followed by an increment. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/string/incrby.mdx LANGUAGE: ts CODE: ``` await redis.set("key", 6); await redis.incrby("key", 4); // returns 10 ``` ---------------------------------------- TITLE: Initialize Serverless Node.js Project DESCRIPTION: Command-line interaction to initialize a new Serverless project for AWS Node.js, creating a project folder named 'histogram-api'. This step guides the user through the initial setup questions for the Serverless Framework. SOURCE: https://upstash.com/docs/redis/tutorials/histogram.mdx LANGUAGE: text CODE: ``` >> serverless Serverless: No project detected. Do you want to create a new one? Yes Serverless: What do you want to make? AWS Node.js Serverless: What do you want to call this project? histogram-api Project successfully created in 'histogram-api' folder. You can monitor, troubleshoot, and test your new service with a free Serverless account. Serverless: Would you like to enable this? No You can run the “serverless” command again if you change your mind later. ``` ---------------------------------------- TITLE: Initialize Upstash Redis in Cloudflare Workers DESCRIPTION: Illustrates how to create an Upstash Redis instance for Cloudflare Workers. It covers initializing with explicit URL/token or loading from the global environment, providing examples for both service worker and module worker contexts. SOURCE: https://upstash.com/docs/redis/sdks/ts/deployment.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis/cloudflare" const redis = new Redis({ url: , token: , }) // or load directly from global env // service worker const redis = Redis.fromEnv() // module worker export default { async fetch(request: Request, env: Bindings) { const redis = Redis.fromEnv(env) // ... } } ``` ---------------------------------------- TITLE: Efficient Redis Connection Management in Serverless JavaScript DESCRIPTION: Provides a JavaScript example for a serverless function handler demonstrating how to initialize a Redis client, perform operations, and ensure the connection is properly closed to manage concurrent connections effectively. SOURCE: https://upstash.com/docs/redis/troubleshooting/max_concurrent_connections.mdx LANGUAGE: javascript CODE: ``` exports.handler = async (event) => { const client = new Redis(process.env.REDIS_URL); /* do stuff with redis */ await client.quit(); /* do other stuff */ return { response: "response" }; }; ``` ---------------------------------------- TITLE: Implement Fixed Window Ratelimiting with Upstash Redis DESCRIPTION: Demonstrates how to create a ratelimiter using the fixed window algorithm, allowing 10 requests per 10 seconds. Examples are provided for both regional and multi-regional Upstash Redis configurations. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/algorithms.mdx LANGUAGE: ts CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.fixedWindow(10, "10 s"), }); ``` LANGUAGE: ts CODE: ``` const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.fixedWindow(10, "10 s"), }); ``` ---------------------------------------- TITLE: Check Redis Key Existence with Python DESCRIPTION: Demonstrates how to use the `exists` command with a Python Redis client. This example shows setting keys, checking their existence, deleting a key, and then re-checking existence to verify the command's behavior. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/exists.mdx LANGUAGE: Python CODE: ``` redis.set("key1", "Hello") redis.set("key2", "World") assert redis.exists("key1", "key2") == 2 redis.delete("key1") assert redis.exists("key1", "key2") == 1 ``` ---------------------------------------- TITLE: TypeScript LPOP Usage Examples DESCRIPTION: Demonstrates how to use the LPOP command in TypeScript with Upstash Redis to pop single or multiple elements from a list, showing the expected output for each scenario. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/list/lpop.mdx LANGUAGE: ts CODE: ``` await redis.rpush("key", "a", "b", "c"); const element = await redis.lpop("key"); console.log(element); // "a" ``` LANGUAGE: ts CODE: ``` await redis.rpush("key", "a", "b", "c"); const element = await redis.lpop("key", 2); console.log(element); // ["a", "b"] ``` ---------------------------------------- TITLE: Publish Message to Redis Channel in Python DESCRIPTION: Demonstrates how to use the `publish` method of the Redis client in Python to send a message to a specified channel. It returns the number of listeners who received the message. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/pubsub/publish.mdx LANGUAGE: py CODE: ``` listeners = redis.publish("my-topic", "my-message") ``` ---------------------------------------- TITLE: Execute Redis SET Command via cURL with Authorization Header DESCRIPTION: Demonstrates how to send a `SET` command to the Upstash REST API using `curl`. It includes the `Authorization: Bearer $TOKEN` header for authentication. SOURCE: https://upstash.com/docs/redis/features/restapi.mdx LANGUAGE: shell CODE: ``` curl https://us1-merry-cat-32748.upstash.io/set/foo/bar \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ``` ---------------------------------------- TITLE: Consume Custom Rates with Upstash Ratelimit DESCRIPTION: This snippet demonstrates how to use the `rate` parameter in the `limit` method to subtract a custom number of tokens from the allowed requests within a window. This feature is particularly useful for scenarios like batch processing or when rate limiting based on the number of tokens consumed rather than just requests. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-py/features.mdx LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), ) # pass rate as 5 to subtract 5 from the number of # allowed requests in the window: identifier = "api" response = ratelimit.limit(identifier, rate=5) ``` ---------------------------------------- TITLE: Python Example: Get All Keys with SCAN DESCRIPTION: Illustrates how to use the SCAN command in Python to retrieve all keys from a Redis database by iterating through the cursor until all results are fetched. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/scan.mdx LANGUAGE: python CODE: ``` # Get all keys cursor = 0 results = [] while True: cursor, keys = redis.scan(cursor, match="*") results.extend(keys) if cursor == 0: break ``` ---------------------------------------- TITLE: Define AWS CDK Stack for Lambda Deployment DESCRIPTION: Defines the AWS CDK stack responsible for provisioning the Lambda function. It configures the Node.js Lambda function, sets environment variables for Redis connection, and creates a public function URL for access. SOURCE: https://upstash.com/docs/redis/tutorials/api_with_cdk.mdx LANGUAGE: typescript CODE: ``` import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new nodejs.NodejsFunction(this, 'CounterFunction', { entry: 'api/counter.ts', handler: 'handler', runtime: lambda.Runtime.NODEJS_20_X, environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, bundling: { format: nodejs.OutputFormat.ESM, target: "node20", nodeModules: ['@upstash/redis'], }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ``` ---------------------------------------- TITLE: Python ZADD Command Usage Examples DESCRIPTION: Illustrative Python examples demonstrating how to use the ZADD command with various options like adding new elements, preventing additions with 'nx', preventing updates with 'xx', and conditional updates with 'gt'. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zadd.mdx LANGUAGE: python CODE: ``` # Add three elements assert redis.zadd("myset", { "one": 1, "two": 2, "three": 3 }) == 3 # No element is added since "one" and "two" already exist assert redis.zadd("myset", { "one": 1, "two": 2 }, nx=True) == 0 # New element is not added since it does not exist assert redis.zadd("myset", { "new-element": 1 }, xx=True) == 0 # Only "three" is updated since new score was greater assert redis.zadd("myset", { "three": 10, "two": 0 }, gt=True) == 1 # Only "three" is updated since new score was greater assert redis.zadd("myset", { "three": 10, "two": 0 }, gt=True) == 1 ``` ---------------------------------------- TITLE: Block Until Ready with Upstash Ratelimit DESCRIPTION: This snippet demonstrates how to use the `block_until_ready` method to pause execution until a rate limit allows a request to pass. It automatically retries if the limit is exceeded, waiting for the next window, and can be configured with a finite timeout period. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-py/features.mdx LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, SlidingWindow from upstash_redis import Redis # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=Redis.from_env(), limiter=SlidingWindow(max_requests=10, window=10), ) response = ratelimit.block_until_ready("id", timeout=30) if not response.allowed: print("Unable to process, even after 30 seconds") else: do_expensive_calculation() print("Here you go!") ``` ---------------------------------------- TITLE: HMGET Command API Reference and Usage Example DESCRIPTION: Documents the Upstash Redis HMGET command, detailing its required arguments (key, fields), expected response format, and provides a TypeScript example demonstrating how to set hash fields and then retrieve specific ones using HMGET. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/hash/hmget.mdx LANGUAGE: APIDOC CODE: ``` HMGET API Documentation: Arguments: key: string (required) Description: The key of the hash. fields: ...string[] (required) Description: One or more fields to get. Response: type: Record (required) Description: An object containing the fields and their values. ``` LANGUAGE: ts CODE: ``` await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); const fields = await redis.hmget("key", "username", "name"); console.log(fields); // { username: "chronark", name: "andreas" } ``` ---------------------------------------- TITLE: Configure DrizzleORM with Basic Upstash Redis Cache DESCRIPTION: Basic configuration of a DrizzleORM instance to use Upstash Redis for caching. By default, caching is opt-in, meaning nothing is cached unless explicitly requested. SOURCE: https://upstash.com/docs/redis/integrations/drizzle.mdx LANGUAGE: typescript CODE: ``` import { upstashCache } from "drizzle-orm/cache/upstash" import { drizzle } from "drizzle-orm/..." const db = drizzle(process.env.DB_URL!, { cache: upstashCache(), }) ``` ---------------------------------------- TITLE: Python Example for JSON.GET Usage DESCRIPTION: Demonstrates how to invoke the JSON.GET method using a Python Redis client to retrieve a value from a JSON document at a specified path. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/json/get.mdx LANGUAGE: Python CODE: ``` value = redis.json.get("key", "$.path.to.somewhere") ``` ---------------------------------------- TITLE: Vote API Endpoint (vote.js) DESCRIPTION: This API endpoint handles the voting mechanism for feature requests. It increments the score of a selected feature request in Redis and prevents multiple votes from the same user by tracking IP addresses in a Redis Set. If an IP has already voted for a specific item, an error message is returned; otherwise, the vote is processed. SOURCE: https://upstash.com/docs/redis/tutorials/roadmapvotingapp.mdx LANGUAGE: javascript CODE: ``` import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const title = body["title"]; let ip = req.headers["x-forwarded-for"] || req.headers["Remote_Addr"] || "NA"; let c = ip === "NA" ? 1 : await redis.sadd("s:" + title, ip); if (c === 0) { redis.quit(); res.json({ error: "You can not vote an item multiple times", }); } else { let v = await redis.zincrby("roadmap", 1, title); redis.quit(); res.json({ body: v, }); } }; ``` ---------------------------------------- TITLE: Configure Apollo Client for Upstash GraphQL in Next.js DESCRIPTION: This JavaScript code sets up the Apollo Client within a Next.js application's `_app.js` file. It configures an `HttpLink` to connect to the Upstash GraphQL endpoint, including an authorization header with a read-only access token, and initializes an `InMemoryCache`. The `ApolloProvider` then wraps the application, making the client accessible to all components. SOURCE: https://upstash.com/docs/redis/tutorials/coin_price_list.mdx LANGUAGE: javascript CODE: ``` import "../styles/globals.css"; import { ApolloClient, ApolloProvider, createHttpLink, InMemoryCache, } from "@apollo/client"; const link = createHttpLink({ uri: "https://graphql-us-east-1.upstash.io/", headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, }); const client = new ApolloClient({ uri: "https://graphql-us-east-1.upstash.io/", cache: new InMemoryCache(), link, }); function MyApp({ Component, pageProps }) { return ( {" "} ); } export default MyApp; ``` ---------------------------------------- TITLE: Verify QStash Messages with Receiver DESCRIPTION: This snippet illustrates how to use the Upstash QStash Receiver to verify incoming messages. The receiver is initialized with current and next signing keys from environment variables. It shows how to call the `verify` method with the signature and body of a received message. SOURCE: https://upstash.com/docs/redis/howto/vercelintegration.mdx LANGUAGE: ts CODE: ``` import { Receiver } from "@upstash/qstash"; const r = new Receiver({ currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY, }); const isValid = await r.verify( signature: "..." body: "..." }) ``` ---------------------------------------- TITLE: Define AWS Lambda Counter Function with Upstash Redis DESCRIPTION: This TypeScript code defines an AWS Lambda handler function that increments a counter stored in Upstash Redis. It initializes the Redis client from environment variables and returns the updated count as a JSON string, suitable for an HTTP response. SOURCE: https://upstash.com/docs/redis/quickstarts/aws-lambda.mdx LANGUAGE: typescript CODE: ``` import { Redis } from '@upstash/redis'; const redis = Redis.fromEnv(); export const handler = async function() { const count = await redis.incr("counter"); return { statusCode: 200, body: JSON.stringify('Counter: ' + count), }; }; ``` ---------------------------------------- TITLE: Node.js AWS Lambda Function for Upstash Redis DESCRIPTION: This Node.js code defines an AWS Lambda handler that connects to an Upstash Redis database using `ioredis`. It demonstrates setting a key-value pair ('foo'/'bar'), retrieving it, and returning the result in a JSON response. Users must replace the placeholder Redis URL with their actual Upstash Redis connection string. SOURCE: https://upstash.com/docs/redis/howto/getstartedawslambda.mdx LANGUAGE: javascript CODE: ``` var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.handler = async (event) => { await client.set("foo", "bar"); let result = await client.get("foo"); let response = { statusCode: 200, body: JSON.stringify({ result: result, }), }; return response; }; ``` ---------------------------------------- TITLE: Define AWS CDK Stack for Counter Lambda Function in TypeScript DESCRIPTION: Configures the AWS CDK stack (`counter-cdk-stack.ts`) to deploy the Python Lambda function. It sets up the Lambda function with asset bundling for Python dependencies, defines runtime and handler, and passes Upstash Redis environment variables. It also creates a Function URL for direct invocation. SOURCE: https://upstash.com/docs/redis/quickstarts/python-aws-lambda.mdx LANGUAGE: typescript CODE: ``` import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as path from 'path'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new lambda.Function(this, 'CounterFunction', { code: lambda.Code.fromAsset(path.join(__dirname, 'api'), { bundling: { image: lambda.Runtime.PYTHON_3_9.bundlingImage, command: [ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output' ], }, }), runtime: lambda.Runtime.PYTHON_3_9, handler: 'index.handler', environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ``` ---------------------------------------- TITLE: Unlink Keys with Upstash Redis (TypeScript) DESCRIPTION: Demonstrates various ways to unlink keys using the `redis.unlink` method in TypeScript, including specifying individual keys and using an array of keys with the spread operator. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/generic/unlink.mdx LANGUAGE: ts CODE: ``` await redis.unlink("key1", "key2"); ``` LANGUAGE: ts CODE: ``` const keys = ["key1", "key2"]; await redis.unlink(...keys) ``` ---------------------------------------- TITLE: Python Example for UNLINK Command DESCRIPTION: Demonstrates how to use the UNLINK command with the Upstash Redis client in Python, asserting the number of keys unlinked. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/unlink.mdx LANGUAGE: python CODE: ``` assert redis.unlink("key1", "key2", "key3") == 3 ``` ---------------------------------------- TITLE: Implement Redis counter on Next.js home page DESCRIPTION: Modifies the Next.js home page (`/app/page.tsx`) to connect to Upstash Redis, increment a counter on each visit, and display its current value. SOURCE: https://upstash.com/docs/redis/quickstarts/ion.mdx LANGUAGE: tsx CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: Store Weather Data in Redis Cache (Elixir) DESCRIPTION: Implements the `cache_weather_response` function, which is responsible for storing weather data in Upstash Redis. It uses the Redix `SET` command with an expiration time (EX) of 8 hours (28800 seconds) to ensure the cached data remains fresh. The function returns `:ok` on successful caching or an error tuple if the operation fails. SOURCE: https://upstash.com/docs/redis/quickstarts/elixir.mdx LANGUAGE: Elixir CODE: ``` defp cache_weather_response(location, weather_data) do case Redix.command(:redix, ["SET", "weather:#{location}", weather_data, "EX", 8 * 60 * 60]) do {:ok, _} -> :ok {:error, _reason} -> {:error, "Failed to cache weather data."} end end ``` ---------------------------------------- TITLE: Python Examples for Redis EVAL Command DESCRIPTION: Demonstrates how to use the `redis.eval` method in Python, including evaluating a script that retrieves a key's value and passing arguments to a Lua script. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/scripts/eval.mdx LANGUAGE: python CODE: ``` script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval(script, keys=["mykey"]) == "Hello" ``` LANGUAGE: python CODE: ``` assert redis.eval("return ARGV[1]", args=["Hello"]) == "Hello" ``` ---------------------------------------- TITLE: Batch Latency Records in JavaScript DESCRIPTION: This JavaScript snippet illustrates a client-side approach for buffering latency values. It collects individual latency measurements into an array and submits them to an API in batches once the array reaches a predefined size, optimizing API calls. SOURCE: https://upstash.com/docs/redis/tutorials/histogram.mdx LANGUAGE: javascript CODE: ``` let records = []; let batchSize = 1000; function recordLatency(value) { records.push(value); if (records.length >= batchSize) { // the below submits the records to the API then empties the records array. submitToAPI(records); } } ``` ---------------------------------------- TITLE: Interact with Redis using Laravel Facade DESCRIPTION: Demonstrates how to use Laravel's `Redis` Facade to perform basic operations like storing and retrieving data. This is useful for direct interactions with the Redis database for simple caching or temporary data storage. SOURCE: https://upstash.com/docs/redis/quickstarts/laravel.mdx LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\Redis; // Storing a value in Redis Redis::set('key', 'value'); // Retrieving a value from Redis $value = Redis::get('key'); ``` ---------------------------------------- TITLE: Ratelimit SDK `limit()` Function Redis Command Costs DESCRIPTION: Details the Redis command count and specific commands executed by the `limit()` function of the Ratelimit SDK for different algorithms (Fixed Window, Sliding Window, Token Bucket), considering cache results and algorithm states. This helps in understanding the cost implications of using the Ratelimit SDK. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/costs.mdx LANGUAGE: APIDOC CODE: ``` Fixed Window Algorithm: Cache Result: Hit/Miss, Algorithm State: First, Command Count: 3, Commands: EVAL, INCR, PEXPIRE Cache Result: Hit/Miss, Algorithm State: Intermediate, Command Count: 2, Commands: EVAL, INCR Cache Result: Miss, Algorithm State: Rate-Limited, Command Count: 2, Commands: EVAL, INCR Cache Result: Hit, Algorithm State: Rate-Limited, Command Count: 0, Commands: _utilized cache_ ``` LANGUAGE: APIDOC CODE: ``` Sliding Window Algorithm: Cache Result: Hit/Miss, Algorithm State: First, Command Count: 5, Commands: EVAL, GET, GET, INCR, PEXPIRE Cache Result: Hit/Miss, Algorithm State: Intermediate, Command Count: 4, Commands: EVAL, GET, GET, INCR Cache Result: Miss, Algorithm State: Rate-Limited, Command Count: 3, Commands: EVAL, GET, GET Cache Result: Hit, Algorithm State: Rate-Limited, Command Count: 0, Commands: _utilized cache_ ``` LANGUAGE: APIDOC CODE: ``` Token Bucket Algorithm: Cache Result: Hit/Miss, Algorithm State: First/Intermediate, Command Count: 4, Commands: EVAL, HMGET, HSET, PEXPIRE Cache Result: Miss, Algorithm State: Rate-Limited, Command Count: 2, Commands: EVAL, HMGET Cache Result: Hit, Algorithm State: Rate-Limited, Command Count: 0, Commands: _utilized cache_ ``` ---------------------------------------- TITLE: Initialize and Use Upstash Ratelimit with Python DESCRIPTION: Demonstrates how to initialize the `Ratelimit` class with a `FixedWindow` limiter and an Upstash Redis instance. It shows how to apply a rate limit to an identifier and handle the `allowed` status from the response. This example assumes `upstash-redis` is also installed and configured. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-py/gettingstarted.mdx LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), # Optional prefix for the keys used in Redis. This is useful # if you want to share a Redis instance with other applications # and want to avoid key collisions. The default prefix is # "@upstash/ratelimit" prefix="@upstash/ratelimit", ) # Use a constant string to limit all requests with a single ratelimit # Or use a user ID, API key or IP address for individual limits. identifier = "api" response = ratelimit.limit(identifier) if not response.allowed: print("Unable to process at this time") else: do_expensive_calculation() print("Here you go!") ``` ---------------------------------------- TITLE: Increment Redis Key Float Value with Python DESCRIPTION: This Python example demonstrates how to use the `incrbyfloat` method to increment a Redis key's float value. It shows setting an initial value and then performing an increment operation. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/incrbyfloat.mdx LANGUAGE: python CODE: ``` redis.set("key", 6) # returns 10.5 redis.incrbyfloat("key", 4,5) ``` ---------------------------------------- TITLE: Configure Upstash Ratelimit Plugin in Strapi DESCRIPTION: Example configuration for the Upstash Ratelimit plugin in Strapi, demonstrating how to enable it, resolve its path, and set up rate limiting strategies with specific methods, paths, algorithms (e.g., fixed-window), tokens, window duration, and a custom prefix. SOURCE: https://upstash.com/docs/redis/integrations/ratelimit/strapi/getting-started.mdx LANGUAGE: typescript CODE: ``` export default () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s" } } ], prefix: "@strapi" } } }); ``` LANGUAGE: javascript CODE: ``` module.exports = () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s" } } ], prefix: "@strapi" } } }); ``` ---------------------------------------- TITLE: Export Upstash Redis Connection Variables DESCRIPTION: Sets environment variables for Upstash Redis host, port, and password. These variables are crucial for applications to establish a connection with the Redis database. SOURCE: https://upstash.com/docs/redis/integrations/celery.mdx LANGUAGE: bash CODE: ``` export UPSTASH_REDIS_HOST= export UPSTASH_REDIS_PORT= export UPSTASH_REDIS_PASSWORD= ``` ---------------------------------------- TITLE: Set Request Timeout for Ratelimit DESCRIPTION: This example shows how to set an optional timeout for the `Ratelimit` instance. If the timeout is reached, the request will be allowed to pass, preventing network issues from rejecting requests. The default timeout is 5 seconds. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/features.mdx LANGUAGE: TypeScript CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), timeout: 1000, // 1 second analytics: true, }); ``` ---------------------------------------- TITLE: TypeScript Example for JSON.STRAPPEND DESCRIPTION: An example demonstrating how to use the JSON.STRAPPEND command with the Upstash Redis client in TypeScript, appending a string value to a specified path within a JSON key. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/json/strappend.mdx LANGUAGE: ts CODE: ``` await redis.json.strappend("key", "$.path.to.str", "abc"); ``` ---------------------------------------- TITLE: Upstash REST API Transaction Request Syntax DESCRIPTION: Documents the HTTP POST request syntax for the Upstash Redis `/multi-exec` endpoint, including the Authorization header and the JSON array body format for multiple Redis commands. SOURCE: https://upstash.com/docs/redis/features/restapi.mdx LANGUAGE: APIDOC CODE: ``` Endpoint: POST /multi-exec Headers: Authorization: Bearer $TOKEN Request Body: Type: JSON Array Format: [ ["CMD_A", "arg0", "arg1", ..., "argN"], ["CMD_B", "arg0", "arg1", ..., "argM"], ... ] Description: A two-dimensional JSON array where each inner array represents a Redis command and its arguments. ``` LANGUAGE: shell CODE: ``` curl -X POST https://us1-merry-cat-32748.upstash.io/multi-exec \ -H "Authorization: Bearer $TOKEN" \ -d ' [ ["CMD_A", "arg0", "arg1", ..., "argN"], ["CMD_B", "arg0", "arg1", ..., "argM"], ... ] ' ``` ---------------------------------------- TITLE: Retrieve All Fields from Redis Hash (TypeScript) DESCRIPTION: Demonstrates how to set multiple fields in a Redis hash using `redis.hset` and then retrieve all fields and their values using `redis.hgetall` in TypeScript. The example shows the expected object output. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/hash/hgetall.mdx LANGUAGE: TypeScript CODE: ``` await redis.hset("key", { field1: "value1", field2: "value2", }); const hash = await redis.hgetall("key"); console.log(hash); // { field1: "value1", field2: "value2" } ``` ---------------------------------------- TITLE: Initialize AWS CDK TypeScript Application DESCRIPTION: Initializes a new AWS CDK application with TypeScript as the primary language. This sets up the basic project structure for CDK development. SOURCE: https://upstash.com/docs/redis/quickstarts/python-aws-lambda.mdx LANGUAGE: shell CODE: ``` cdk init app --language typescript ``` ---------------------------------------- TITLE: ZUNIONSTORE Command Usage Examples (TypeScript) DESCRIPTION: Illustrates various use cases of the ZUNIONSTORE command in TypeScript, including basic set union, applying custom weights to input sets, and using different aggregation methods like 'sum'. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/zset/zunionstore.mdx LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore("destination", 2, ["key1", "key2"]); console.log(res) // 2 ``` LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore( "destination", 2, ["key1", "key2"], { weights: [2, 3] }, ); console.log(res) // 2 ``` LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore( "destination", 2, ["key1", "key2"], { aggregate: "sum" }, ); console.log(res) // 2 ``` ---------------------------------------- TITLE: Redis Streams Commands DESCRIPTION: Documents the Streams commands supported by Upstash Redis, providing a powerful append-only data structure for event logging and messaging. These commands allow adding entries, reading from streams, managing consumer groups, and trimming streams. SOURCE: https://upstash.com/docs/redis/overall/rediscompatibility.mdx LANGUAGE: APIDOC CODE: ``` XACK XADD XAUTOCLAIM XCLAIM XDEL XGROUP XINFO GROUPS XINFO CONSUMERS XLEN XPENDING XRANGE XREAD XREADGROUP XREVRANGE XTRIM ``` ---------------------------------------- TITLE: Upstash Redis SET Command Examples (TypeScript) DESCRIPTION: Practical TypeScript examples demonstrating various ways to use the `redis.set` command, including basic key-value assignment, setting expirations, and conditional updates. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/string/set.mdx LANGUAGE: ts CODE: ``` await redis.set("my-key", {my: "value"}); ``` LANGUAGE: ts CODE: ``` await redis.set("my-key", {my: "value"}, { ex: 60 }); ``` LANGUAGE: ts CODE: ``` await redis.set("my-key", {my: "value"}, { xx: true }); ``` ---------------------------------------- TITLE: Initialize Sliding Window Ratelimit with Upstash Redis DESCRIPTION: Shows how to configure a sliding window ratelimiter using `upstash_ratelimit` and `upstash_redis`. This setup defines a limit of 10 requests per 10-second window, leveraging the rolling window concept. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-py/algorithms.mdx LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, SlidingWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=SlidingWindow(max_requests=10, window=10), ) ``` ---------------------------------------- TITLE: Ratelimit blockUntilReady Usage Example DESCRIPTION: Illustrates how to use `ratelimit.blockUntilReady` to create a ratelimiter and wait for a request to be allowed. It shows initializing a ratelimiter and handling the success or failure of the `blockUntilReady` call. Note: `Date.now()` behavior differs in Cloudflare Workers. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/methods.mdx LANGUAGE: ts CODE: ``` // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, }); // `blockUntilReady` returns a promise that resolves as soon as the request is allowed to be processed, or after 30 seconds const { success } = await ratelimit.blockUntilReady("id", 30_000); if (!success) { return "Unable to process, even after 30 seconds"; } doExpensiveCalculation(); return "Here you go!"; ``` ---------------------------------------- TITLE: LPUSH Command Usage Example in Python DESCRIPTION: Demonstrates how to use the LPUSH command with a Redis client in Python to add multiple elements to the head of a list, and then verifies the list's content and order using LRANGE. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/list/lpush.mdx LANGUAGE: Python CODE: ``` assert redis.lpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] ``` ---------------------------------------- TITLE: Remove Members from Redis Set (TypeScript) DESCRIPTION: This TypeScript example demonstrates how to first add members to a Redis set using `sadd` and then remove specific members using the `srem` command. It also shows the returned count of successfully removed members. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/set/srem.mdx LANGUAGE: ts CODE: ``` await redis.sadd("set", "a", "b", "c"); const removed = await redis.srem("set", "a", "b", "d"); console.log(removed); // 2 ``` ---------------------------------------- TITLE: Dump and Import Redis Data using upstash-redis-dump DESCRIPTION: This snippet demonstrates how to use the `upstash-redis-dump` tool to export data from a Redis instance. It shows the command-line arguments required to connect to a specific Redis host, port, database, and password, with TLS enabled, and redirect the output to a local file named `redis.dump`. The output also confirms the number of keys dumped. SOURCE: https://upstash.com/docs/redis/howto/importexport.mdx LANGUAGE: shell CODE: ``` $ upstash-redis-dump -db 0 -host eu1-moving-loon-6379.upstash.io -port 6379 -pass PASSWORD -tls > redis.dump Database 0: 9 keys dumped ``` ---------------------------------------- TITLE: Import Upstash Redis for Edge Environments DESCRIPTION: This TypeScript snippet shows specific import paths for the Upstash Redis client when deploying to Cloudflare Workers or Fastly Compute@Edge, allowing `Ratelimit` to connect to Redis in these environments. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis/cloudflare"; // for cloudflare workers and pages import { Redis } from "@upstash/redis/fastly"; // for fastly compute@edge ``` ---------------------------------------- TITLE: Authenticate REST API with Authorization Header DESCRIPTION: Demonstrates how to authenticate an Upstash Redis REST API request by including the bearer token in the 'Authorization' HTTP header. This method is suitable for secure server-side or trusted client-side applications. SOURCE: https://upstash.com/docs/redis/features/restapi.mdx LANGUAGE: shell CODE: ``` curl -X POST https://us1-merry-cat-32748.upstash.io/info \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ``` ---------------------------------------- TITLE: Execute Laravel Database Migrations DESCRIPTION: Artisan command to run all pending database migrations. This command creates or updates the database tables according to the defined schema files, including the 'todos' table. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: shell CODE: ``` php artisan migrate ``` ---------------------------------------- TITLE: Chain Commands in Redis Pipelines in Python DESCRIPTION: This snippet illustrates a more concise way to add multiple commands to a Redis pipeline by chaining method calls. This syntax can improve readability for sequences of operations within a pipeline. SOURCE: https://upstash.com/docs/redis/sdks/py/features.mdx LANGUAGE: python CODE: ``` pipeline = redis.pipeline() pipeline.set("foo", 1).incr("foo").get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ``` ---------------------------------------- TITLE: MSET Command API Reference DESCRIPTION: Detailed API documentation for the MSET command, outlining its required parameters and expected response. This command counts as a single operation for billing. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/string/mset.mdx LANGUAGE: APIDOC CODE: ``` MSET Command: Description: Set multiple keys in one go. Billing: Counts as a single command. Arguments: params: Record (required) Description: An object where the keys are the keys to set, and the values are the values to set. Response: Type: string (required) Value: "OK" ``` ---------------------------------------- TITLE: Upstash Redis KEYS Command API Reference DESCRIPTION: Documents the `KEYS` command for Upstash Redis, detailing its arguments, response format, and a critical warning regarding its performance impact in production environments. This command allows retrieving keys based on a glob-style pattern. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/keys.mdx LANGUAGE: APIDOC CODE: ``` KEYS Command: Description: Returns all keys matching pattern. Warning: This command may block the DB for a long time, depending on its size. We advice against using it in production. Use SCAN instead. Arguments: match (str, required): A glob-style pattern. Use `*` to match all keys. Response: type: List[str] description: Array of keys matching the pattern. ``` ---------------------------------------- TITLE: Next.js App Router Project Initialization and Upstash Redis Installation DESCRIPTION: This snippet provides the shell commands to create a new Next.js application using the App Router. It also includes the command to install the `@upstash/redis` package, which is necessary for interacting with Upstash Redis. SOURCE: https://upstash.com/docs/redis/quickstarts/nextjs-app-router.mdx LANGUAGE: shell CODE: ``` npx create-next-app@latest cd my-app npm install @upstash/redis ``` ---------------------------------------- TITLE: Next.js Project Setup with Upstash Redis DESCRIPTION: This code block provides the necessary commands to initialize a new Next.js application using the App Router and install the `@upstash/redis` package. These steps are foundational for setting up the project environment before integrating Redis. SOURCE: https://upstash.com/docs/redis/tutorials/nextjs_with_redis.mdx LANGUAGE: shell CODE: ``` npx create-next-app@latest cd my-app npm install @upstash/redis ``` ---------------------------------------- TITLE: API Setup: Implement Next.js API Route with Upstash Redis Counter DESCRIPTION: Creates a Next.js API route at `/api/hello` that initializes an Upstash Redis client using the bound secrets. This route increments a 'counter' key in Redis on each request and returns the current count as a JSON response. SOURCE: https://upstash.com/docs/redis/quickstarts/sst-v2.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis"; import type { NextApiRequest, NextApiResponse } from "next"; import { Config } from "sst/node/config"; const redis = new Redis({ url: Config.UPSTASH_REDIS_REST_URL, token: Config.UPSTASH_REDIS_REST_TOKEN, }); export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const count = await redis.incr("counter"); res.status(200).json({ count }); } ``` ---------------------------------------- TITLE: Create and Execute Redis Pipeline with Upstash (TypeScript) DESCRIPTION: This snippet demonstrates how to use the Upstash Redis client to create and execute a command pipeline. Pipelining allows sending multiple commands in a single HTTP request, improving efficiency. It's important to note that pipeline execution is not atomic, meaning other commands can interleave. The `exec()` method returns an array of responses, corresponding to each command in the pipeline. SOURCE: https://upstash.com/docs/redis/sdks/ts/pipelining/pipeline-transaction.mdx LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ /* auth */ }); const p = redis.pipeline(); // Now you can chain multiple commands to create your pipeline: p.set("key", 2); p.incr("key"); // or inline: p.hset("key2", "field", { hello: "world" }).hvals("key2"); // Execute the pipeline once you are done building it: // `exec` returns an array where each element represents the response of a command in the pipeline. // You can optionally provide a type like this to get a typed response. const res = await p.exec<[Type1, Type2, Type3]>(); ``` ---------------------------------------- TITLE: Perform Per-Query Caching with DrizzleORM DESCRIPTION: Demonstrates how to explicitly enable caching for individual DrizzleORM queries using the `.$withCache()` method. This is the default behavior when global caching is not enabled. SOURCE: https://upstash.com/docs/redis/integrations/drizzle.mdx LANGUAGE: typescript CODE: ``` await db.insert(users).value({ email: "cacheman@upstash.com" }); // 👇 reads from cache await db.select().from(users).$withCache() ``` ---------------------------------------- TITLE: TypeScript XADD with Trimming Options DESCRIPTION: Illustrates appending an entry to a Redis stream while simultaneously applying trimming rules. This example uses `MAXLEN` to limit the stream's length to 1000 entries. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/stream/xadd.mdx LANGUAGE: ts CODE: ``` await redis.xadd(key, "*", { name: "John Doe", age: 30 }, { trim: { type: "MAXLEN", threshold: 1000, comparison: "=", }, }); ``` ---------------------------------------- TITLE: Node.js Bull.js Consumer for Upstash Redis DESCRIPTION: This JavaScript code sets up a Bull.js queue to process 'employee registration' events. It connects to an Upstash Redis instance, configures queue settings to optimize for Upstash quotas, and defines a job processor function. Users must replace placeholder Redis connection details with their own. SOURCE: https://upstash.com/docs/redis/tutorials/job_processing.mdx LANGUAGE: javascript CODE: ``` var Queue = require("bull"); var settings = { stalledInterval: 300000, // How often check for stalled jobs (use 0 for never checking). guardInterval: 5000, // Poll interval for delayed jobs and added jobs. drainDelay: 300, // A timeout for when the queue is in drained state (empty waiting for jobs). }; var taskQueue = new Queue( "employee registration", { redis: { port: 32016, host: "us1-upward-ant-32016.upstash.io", password: "ake4ff120d6b4216df220736be7eab087", tls: {}, }, }, settings ); taskQueue .process(function (job, done) { console.log(job.data); // TODO process the new employee event done(); }) .catch((err) => { console.log(err); }); ``` ---------------------------------------- TITLE: Parse Redis connection details from REDIS_URL environment variable in Elixir DESCRIPTION: This Elixir code block demonstrates how to extract the password, host, and port from the `REDIS_URL` environment variable. It uses a regular expression to parse the URL string, which is crucial for dynamically connecting to the Upstash Redis instance, especially when deployed on platforms like Fly.io that provide connection details via environment variables. SOURCE: https://upstash.com/docs/redis/quickstarts/elixir.mdx LANGUAGE: Elixir CODE: ``` def start(_type, _args) do [_, password, host, port] = Regex.run( ~r{(.+):(.+)@(.+):(\d+)}, System.get_env("REDIS_URL"), capture: :all_but_first ) port = elem(Integer.parse(port), 0) # ... end ``` ---------------------------------------- TITLE: Create Dockerfile for Node.js Application DESCRIPTION: Provides a multi-stage Dockerfile for building and running a Node.js application, including dependency installation, user setup, and port exposure. SOURCE: https://upstash.com/docs/redis/quickstarts/koyeb.mdx LANGUAGE: dockerfile CODE: ``` FROM node:18-alpine AS base FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci FROM base AS runner WORKDIR /app RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nodejs COPY --from=deps /app/node_modules ./node_modules COPY . . USER node EXPOSE 3000 ENV PORT 3000 CMD ["npm", "run", "start"] ``` ---------------------------------------- TITLE: Connect to Upstash Redis using redigo (Go) DESCRIPTION: This example shows how to connect to an Upstash Redis database using the `redigo` library in Go. It dials a TCP connection with TLS, authenticates with the password, and then performs `SET` and `GET` commands. SOURCE: https://upstash.com/docs/redis/howto/connectclient.mdx LANGUAGE: go CODE: ``` func main() { c, err := redis.Dial("tcp", "YOUR_ENDPOINT:YOUR_PORT", redis.DialUseTLS(true)) if err != nil { panic(err) } _, err = c.Do("AUTH", "YOUR_PASSWORD") if err != nil { panic(err) } _, err = c.Do("SET", "foo", "bar") if err != nil { panic(err) } value, err := redis.String(c.Do("GET", "foo")) if err != nil { panic(err) } println(value) } ``` ---------------------------------------- TITLE: Configure Laravel session to use Redis DESCRIPTION: Sets the `SESSION_DRIVER` variable in the Laravel `.env` file to 'redis'. This ensures that all session data for the Laravel application is stored in the Upstash Redis database, providing fast and reliable session management. SOURCE: https://upstash.com/docs/redis/quickstarts/laravel.mdx LANGUAGE: shell CODE: ``` SESSION_DRIVER="redis" ``` ---------------------------------------- TITLE: TypeScript Example for SISMEMBER DESCRIPTION: An example demonstrating how to use the SISMEMBER command with the `upstash-redis` client in TypeScript, including adding members to a set and checking for existence. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/set/sismember.mdx LANGUAGE: ts CODE: ``` await redis.sadd("set", "a", "b", "c"); const isMember = await redis.sismember("set", "a"); console.log(isMember); // 1 ``` ---------------------------------------- TITLE: Python Example for Redis GETDEL Command DESCRIPTION: Demonstrates the usage of the `GETDEL` command in Python, showing how it retrieves a key's value and then deletes the key, verifying its subsequent absence. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/getdel.mdx LANGUAGE: py CODE: ``` redis.set("key", "value") assert redis.getdel("key") == "value" assert redis.get("key") == None ``` ---------------------------------------- TITLE: FastAPI Session Management Endpoints Overview DESCRIPTION: This section outlines the core API endpoints for session management. It details the functionality of the /login/ endpoint for session creation, the /profile/ endpoint for session retrieval and update, and the /logout/ endpoint for session termination, all leveraging Redis for session data storage. SOURCE: https://upstash.com/docs/redis/tutorials/python_session.mdx LANGUAGE: APIDOC CODE: ``` /login/ Endpoint: - Generates a unique session ID using uuid.uuid4(). - Stores the session data in Redis using the session ID as the key. - Sets a cookie named session_id with the generated session ID. - Returns a success message along with the session ID. /profile/ Endpoint: - Retrieves the session ID from the cookie. - Fetches the session data from Redis using the session ID. - Updates the session expiration time. - Returns the session ID and session data. /logout/ Endpoint: - Deletes the session data from Redis using the session ID. - Clears the session_id cookie. ``` ---------------------------------------- TITLE: Execute Redis Pipeline using Upstash TS SDK DESCRIPTION: Demonstrates how to use the `pipeline` method in the Upstash Redis TypeScript SDK to batch multiple commands. Commands in a pipeline are not atomic, allowing other client commands to execute in between. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/transaction.mdx LANGUAGE: typescript CODE: ``` const p = redis.pipeline(); p.set("foo", "bar"); p.get("foo"); const res = await p.exec(); ``` ---------------------------------------- TITLE: RPUSH Command API Reference and Usage DESCRIPTION: Comprehensive API documentation for the RPUSH command, including its required arguments (key, elements), the type of response (list length), and a TypeScript example demonstrating how to use the command with an Upstash Redis client. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/list/rpush.mdx LANGUAGE: APIDOC CODE: ``` RPUSH Command: Description: Push an element at the end of the list. Arguments: key: Type: string Required: true Description: The key of the list. elements: Type: ...TValue[] Required: true Description: One or more elements to push at the end of the list. Response: Type: number Required: true Description: The length of the list after the push operation. ``` LANGUAGE: TypeScript CODE: ``` const length1 = await redis.rpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.rpush("key", "d"); console.log(length2); // 4 ``` ---------------------------------------- TITLE: Python Example for RPUSH Command DESCRIPTION: Illustrates how to use the RPUSH command in Python to add elements to a Redis list and verify the list's contents. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/list/rpush.mdx LANGUAGE: python CODE: ``` assert redis.rpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["one", "two", "three"] ``` ---------------------------------------- TITLE: Python Example for EVAL_RO with Key Access DESCRIPTION: Demonstrates how to use `eval_ro` in Python to execute a Lua script that retrieves a value from a specified key, asserting the correct return value. This example sets a key first and then evaluates a script that reads it. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/scripts/eval_ro.mdx LANGUAGE: python CODE: ``` script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval_ro(script, keys=["mykey"]) == "Hello" ``` ---------------------------------------- TITLE: Import data to global Upstash Redis database DESCRIPTION: Imports data from the `redis.dump` file into the specified global Upstash Redis database. This command pipes the dump file content to `upstash-redis-dump` with the `-import` flag, requiring the global database's host, port, and password. SOURCE: https://upstash.com/docs/redis/howto/migratefromregionaltoglobal.mdx LANGUAGE: bash CODE: ``` cat redis.dump | upstash-redis-dump -db 0 -host YOUR_GLOBAL_HOST -port 6379 -pass YOUR_PASSWORD -tls -import ``` ---------------------------------------- TITLE: Install Upstash Redis Client DESCRIPTION: Installs the `@upstash/redis` package, a client library for interacting with Upstash Redis, into the project. This dependency is crucial for connecting to the Redis database from the Azure Function. SOURCE: https://upstash.com/docs/redis/quickstarts/azure-functions.mdx LANGUAGE: shell CODE: ``` npm install @upstash/redis ``` ---------------------------------------- TITLE: Define Node.js Dependencies in package.json DESCRIPTION: Configuration for `package.json` to include `@upstash/redis` as a dependency. This ensures the Upstash Redis client library is available for the project. SOURCE: https://upstash.com/docs/redis/tutorials/using_serverless_framework.mdx LANGUAGE: json CODE: ``` { "dependencies": { "@upstash/redis": "latest" } } ``` ---------------------------------------- TITLE: PTTL Command Usage Example (Python) DESCRIPTION: Demonstrates the usage of the PTTL command in Python with a Redis client. This example shows how to set a key, check its initial PTTL (which is -1 for no expiration), set an expiration, check PTTL again (which will be positive), and then persist the key to remove expiration, returning PTTL to -1. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/pttl.mdx LANGUAGE: python CODE: ``` redis.set("key1", "Hello") assert redis.pttl("key1") == -1 redis.expire("key1", 1000) assert redis.pttl("key1") > 0 redis.persist("key1") assert redis.pttl("key1") == -1 ``` ---------------------------------------- TITLE: Python Example for Redis INCRBY Usage DESCRIPTION: Illustrates the usage of the `incrby` method in Python with a Redis client. It demonstrates setting an initial value for a key, incrementing it by a specified amount, and asserting the correct resulting value. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/incrby.mdx LANGUAGE: Python CODE: ``` redis.set("key", 6) assert redis.incrby("key", 4) == 10 ``` ---------------------------------------- TITLE: TypeScript Example: SPOP Multiple Members DESCRIPTION: Illustrates using the SPOP command with a count parameter in TypeScript to remove and return multiple random members from a Redis set. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/set/spop.mdx LANGUAGE: TypeScript CODE: ``` await redis.sadd("set", "a", "b", "c"); const popped = await redis.spop("set", 2); console.log(popped); // ["a", "b"] ``` ---------------------------------------- TITLE: Initialize Ratelimit Client with Deny List Protection DESCRIPTION: Demonstrates how to initialize the Upstash Ratelimit client with `enableProtection` set to `true` to activate deny list checking. This configuration allows the client to block requests based on predefined deny lists for IPs, user agents, countries, or identifiers. It also shows how to enable analytics. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/traffic-protection.mdx LANGUAGE: tsx CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), enableProtection: true, analytics: true, }); ``` ---------------------------------------- TITLE: Python Example: JSON.SET with XX Option DESCRIPTION: Shows how to use the `xx=true` option with `redis.json.set` to set a JSON value only if the specified path already exists within the key. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/json/set.mdx LANGUAGE: python CODE: ``` value = ... redis.json.set(key, "$.path", value, xx=true) ``` ---------------------------------------- TITLE: Python XADD with Trimming Example DESCRIPTION: Illustrates how to use the XADD command in Python with stream trimming options. This example uses MAXLEN trimming to keep the stream size below a specified threshold. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/stream/xadd.mdx LANGUAGE: py CODE: ``` redis.xadd(key, "*", { name: "John Doe", age: 30 }, { trim: { type: "MAXLEN", threshold: 1000, comparison: "=", }, }) ``` ---------------------------------------- TITLE: Check Multiple Members in Redis Set (TypeScript) DESCRIPTION: Demonstrates how to add members to a Redis set using `sadd` and then check for the existence of multiple members using `smismember` in TypeScript, logging the resulting array of boolean indicators. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/set/smismember.mdx LANGUAGE: ts CODE: ``` await redis.sadd("set", "a", "b", "c"); const members = await redis.smismember("set", ["a", "b", "d"]); console.log(members); // [1, 1, 0] ``` ---------------------------------------- TITLE: Example ZINCRBY Usage in Python DESCRIPTION: Demonstrates how to use the ZINCRBY command with an Upstash Redis client in Python, including adding initial members to a sorted set and asserting the incremented score. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zincrby.mdx LANGUAGE: python CODE: ``` redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zincrby("myset", 2, "one") == 3 ``` ---------------------------------------- TITLE: TypeScript HDEL Usage Example DESCRIPTION: Example demonstrating how to use the HDEL command with the Upstash Redis client in TypeScript. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/hash/hdel.mdx LANGUAGE: ts CODE: ``` await redis.hdel(key, 'field1', 'field2'); // returns 5 ``` ---------------------------------------- TITLE: Python Example for ZRANK Command DESCRIPTION: Demonstrates how to use the ZRANK command with a Python Redis client. It shows adding members to a sorted set and then asserting the ranks of existing and non-existing members. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zrank.mdx LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrank("myset", "a") == 0 assert redis.zrank("myset", "d") == None assert redis.zrank("myset", "b") == 1 assert redis.zrank("myset", "c") == 2 ``` ---------------------------------------- TITLE: Python Example: Iterate All Fields in a Redis Hash with HSCAN DESCRIPTION: Demonstrates how to use the `hscan` method in Python to retrieve all fields from a Redis hash iteratively until the cursor returns to 0. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/hash/hscan.mdx LANGUAGE: python CODE: ``` # Get all members of a hash. cursor = 0 results = [] while True: cursor, keys = redis.hscan("myhash", cursor, match="*") results.extend(keys) if cursor == 0: break ``` ---------------------------------------- TITLE: Python ZUNIONSTORE with Weights DESCRIPTION: Shows how to apply custom weights to input sets when using ZUNIONSTORE. This example demonstrates how weights influence the final scores of members in the resulting set, affecting the aggregated score. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zunionstore.mdx LANGUAGE: py CODE: ``` redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zunionstore(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ``` ---------------------------------------- TITLE: TypeScript Example for JSON.ARRINSERT DESCRIPTION: This TypeScript code snippet demonstrates how to use the `redis.json.arrinsert` method to insert multiple values into a JSON array at a specified path and index within a Redis key. It shows how to capture the returned array length. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/json/arrinsert.mdx LANGUAGE: ts CODE: ``` const length = await redis.json.arrinsert("key", "$.path.to.array", 2, "a", "b"); ``` ---------------------------------------- TITLE: TypeScript Example: SPOP Single Member DESCRIPTION: Demonstrates how to use the SPOP command in TypeScript to remove and return a single random member from a Redis set. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/set/spop.mdx LANGUAGE: TypeScript CODE: ``` await redis.sadd("set", "a", "b", "c"); const popped = await redis.spop("set"); console.log(popped); // "a" ``` ---------------------------------------- TITLE: Deployment: Set Production Secrets for Upstash Redis DESCRIPTION: Configures the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` secrets specifically for the production deployment stage using the SST CLI. These will be used when deploying to a live environment. SOURCE: https://upstash.com/docs/redis/quickstarts/sst-v2.mdx LANGUAGE: shell CODE: ``` npx sst secrets set --stage prod UPSTASH_REDIS_REST_URL npx sst secrets set --stage prod UPSTASH_REDIS_REST_TOKEN ``` ---------------------------------------- TITLE: Check if a field exists in Redis hash (Python) DESCRIPTION: Demonstrates how to use the `hexists` command with a Redis client in Python. It first sets a field in a hash and then asserts that the field correctly exists. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/hash/hexists.mdx LANGUAGE: py CODE: ``` redis.hset("key", "field", "value") assert redis.hexists("key", "field") == True ``` ---------------------------------------- TITLE: ZINTERSTORE API Reference DESCRIPTION: Comprehensive documentation for the ZINTERSTORE command, detailing its arguments, their types, default values, and the expected response structure. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zinterstore.mdx LANGUAGE: APIDOC CODE: ``` ZINTERSTORE: Description: Calculates the intersection of sets and stores the result in a key. Arguments: destination (str, required): The key to store the result in. keys (List[str], required): The keys of the sets to compare. weights (List[float], optional, default=None): The weights to apply to the sets. aggregate ("SUM" | "MIN" | "MAX", optional, default="sum"): The aggregation function to apply to the sets. withscores (bool, optional, default=false): Whether to include scores in the result. Response: (integer, required): The number of elements in the resulting set. ``` ---------------------------------------- TITLE: Python Example for HVALS Command DESCRIPTION: Demonstrates how to use the `hset` method to populate a hash and then retrieve all its values using the `hvals` method with the Upstash Redis client in Python, including an assertion for verification. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/hash/hvals.mdx LANGUAGE: python CODE: ``` redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hvals("myhash") == ["Hello", "World"] ``` ---------------------------------------- TITLE: Python Example for HEXPIRE Usage DESCRIPTION: Demonstrates how to use the `hexpire` command in Python with the `upstash-redis` client. This example shows a basic hash set operation followed by setting an expiry of 1 second on a specific field within the hash. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/hash/hexpire.mdx LANGUAGE: python CODE: ``` redis.hset(hash_name, field, value) assert redis.hexpire(hash_name, field, 1) == [1] ``` ---------------------------------------- TITLE: INCR Command DESCRIPTION: Increment the integer value of a key by one. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/overview.mdx LANGUAGE: Redis CODE: ``` INCR ``` ---------------------------------------- TITLE: STRLEN Command DESCRIPTION: Get the length of the value stored in a key. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/overview.mdx LANGUAGE: Redis CODE: ``` STRLEN ``` ---------------------------------------- TITLE: Connect to Redis via Fly.io Tunnel in Node.js DESCRIPTION: This Node.js example demonstrates how to configure a Redis client to connect using the local address provided by the `fly redis connect` tunnel during development. It dynamically switches to a production environment variable for deployment, ensuring flexibility. SOURCE: https://upstash.com/docs/redis/quickstarts/fly.mdx LANGUAGE: javascript CODE: ``` const redis = require("redis"); // Local Redis URL for development const LOCAL_REDIS_URL = 'redis://localhost:10000'; // Replace with your actual local address const REDIS_URL = process.env.NODE_ENV === 'development' ? LOCAL_REDIS_URL : process.env.REDIS_URL; const client = redis.createClient({ url: REDIS_URL }); client.on("error", function(error) { console.error(error); }); // Rest of your Redis-related code ``` ---------------------------------------- TITLE: Execute Custom Redis Commands in Python DESCRIPTION: This example illustrates how to execute Redis commands that are not explicitly implemented in the `upstash-redis` client. The `execute` function of the client instance can be used by passing the command and its arguments as a Python list. SOURCE: https://upstash.com/docs/redis/sdks/py/features.mdx LANGUAGE: python CODE: ``` redis.execute(["XLEN", "test_stream"]) ``` ---------------------------------------- TITLE: Python Example for MSETNX DESCRIPTION: Illustrates how to use the MSETNX command with the Upstash Redis Python client, setting multiple key-value pairs. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/msetnx.mdx LANGUAGE: python CODE: ``` redis.msetnx({ key1: 1, key2: "hello", key3: { a: 1, b: "hello" } }) ``` ---------------------------------------- TITLE: Python Example for ZSCORE DESCRIPTION: Demonstrates how to use the ZSCORE command in Python. This example first adds members to a sorted set and then asserts the score of a specific member. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zscore.mdx LANGUAGE: py CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zscore("myset", "a") == 1 ``` ---------------------------------------- TITLE: Create Upstash Redis Database with Terraform DESCRIPTION: This snippet demonstrates how to define an Upstash Redis database resource using Terraform. It requires a database name, a specific region for deployment, and the type of database (e.g., 'free' or 'paid'). SOURCE: https://upstash.com/docs/redis/howto/terraformprovider.mdx LANGUAGE: Terraform CODE: ``` resource "upstash_database" "mydb" { database_name = "testdblstr" region = "eu-west-1" type = "free" } ``` ---------------------------------------- TITLE: Retrieve Weather Data from Redis Cache (Elixir) DESCRIPTION: Implements the `fetch_weather_from_cache` function, which uses the Redix client to query Upstash Redis for cached weather information. It constructs a cache key based on the location and decodes the JSON response if found. The function returns `{:ok, decoded_data}` for a cache hit, `{:error, :not_found}` for a miss, or an error message for other failures. SOURCE: https://upstash.com/docs/redis/quickstarts/elixir.mdx LANGUAGE: Elixir CODE: ``` defp fetch_weather_from_cache(location) do case Redix.command(:redix, ["GET", "weather:#{location}"]) do {:ok, nil} -> {:error, :not_found} {:ok, cached_weather_json} -> {:ok, Jason.decode!(cached_weather_json)} {:error, _reason} -> {:error, "Failed to fetch weather data from cache."} end end ``` ---------------------------------------- TITLE: Upstash Pipelining API Request Syntax Example DESCRIPTION: Illustrates the `curl` command syntax for sending multiple Redis commands as a batch to the Upstash `/pipeline` endpoint. Commands are sent as a two-dimensional JSON array in the request body. SOURCE: https://upstash.com/docs/redis/features/restapi.mdx LANGUAGE: shell CODE: ``` curl -X POST https://us1-merry-cat-32748.upstash.io/pipeline \ -H "Authorization: Bearer $TOKEN" \ -d ' [ ["CMD_A", "arg0", "arg1", ..., "argN"], ["CMD_B", "arg0", "arg1", ..., "argM"], ... ] ' ``` ---------------------------------------- TITLE: Upstash REST API Transaction Discarded Response DESCRIPTION: Describes the JSON object response format when an entire Upstash Redis transaction is discarded due to a global error. SOURCE: https://upstash.com/docs/redis/features/restapi.mdx LANGUAGE: APIDOC CODE: ``` Response Body: Type: JSON Object Format: { "error": "ERR ..." } Description: A single JSON object containing an 'error' field if the entire transaction is discarded. ``` LANGUAGE: json CODE: ``` { "error": "ERR ..." } ``` ---------------------------------------- TITLE: Configure Upstash Redis Connection in Laravel .env DESCRIPTION: Environment variables for connecting Laravel to an Upstash Redis database. This includes the Redis host, port, and password, which are essential for establishing a connection to the Redis server. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: .env CODE: ``` REDIS_HOST="" REDIS_PORT=6379 REDIS_PASSWORD="" ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables in wrangler.toml DESCRIPTION: Adds `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` as environment variables to the Cloudflare Worker's `wrangler.toml` file, making them securely accessible within the worker's runtime. SOURCE: https://upstash.com/docs/redis/tutorials/cloudflare_workers_with_redis.mdx LANGUAGE: toml CODE: ``` # existing config [vars] UPSTASH_REDIS_REST_URL = UPSTASH_REDIS_REST_TOKEN = ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables DESCRIPTION: Sets up environment variables for connecting to the Upstash Redis database. These variables, `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`, are required for the application to authenticate and communicate with Redis. SOURCE: https://upstash.com/docs/redis/tutorials/python_session.mdx LANGUAGE: Bash CODE: ``` UPSTASH_REDIS_REST_URL=your_upstash_redis_url UPSTASH_REDIS_REST_TOKEN=your_upstash_redis_token ``` ---------------------------------------- TITLE: Python Example: Removing Elements with LREM DESCRIPTION: Illustrates the usage of the `lrem` method in Python with the Upstash Redis client. This example demonstrates pushing elements to a list, then using `lrem` to remove specific occurrences of an element, and finally asserting the modified list content. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/list/lrem.mdx LANGUAGE: py CODE: ``` redis.rpush("mylist", "one", "two", "three", "two", "one") assert redis.lrem("mylist", 2, "two") == 2 assert redis.lrange("mylist", 0, -1) == ["one", "three", "one"] ``` ---------------------------------------- TITLE: Dockerfile for Node.js Express Application on Cloud Run DESCRIPTION: This Dockerfile defines the steps to build a Docker image for the Node.js Express application. It uses a lightweight Node.js base image, sets the working directory, copies `package.json` files, installs dependencies, and prepares the environment for running the application in a containerized manner suitable for Google Cloud Run. SOURCE: https://upstash.com/docs/redis/tutorials/cloud_run_sessions.mdx LANGUAGE: dockerfile CODE: ``` # Use the official lightweight Node.js 12 image. # https://hub.docker.com/_/node FROM node:12-slim # Create and change to the app directory. WORKDIR /usr/src/app # Copy application dependency manifests to the container image. # A wildcard is used to ensure both package.json AND package-lock.json are copied. # Copying this separately prevents re-running npm install on every code change. COPY package*.json ./ # Install dependencies. RUN npm install ``` ---------------------------------------- TITLE: Python Example for Redis LSET Usage DESCRIPTION: A Python code example demonstrating how to use the LSET command with a Redis client. It illustrates pushing elements to a list, setting a value at a valid index, and verifying the list content, as well as handling attempts to set values at out-of-range indices. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/list/lset.mdx LANGUAGE: python CODE: ``` redis.rpush("mylist", "one", "two", "three") assert redis.lset("mylist", 1, "Hello") == True assert redis.lrange("mylist", 0, -1) == ["one", "Hello", "three"] assert redis.lset("mylist", 5, "Hello") == False assert redis.lrange("mylist", 0, -1) == ["one", "Hello", "three"] ``` ---------------------------------------- TITLE: Remove Members from Sorted Set (TypeScript) DESCRIPTION: Demonstrates how to use the `zrem` command in TypeScript to remove one or more members from a sorted set in Upstash Redis. The command takes the sorted set key and the members to be removed as arguments. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/zset/zrem.mdx LANGUAGE: ts CODE: ``` await redis.zrem("key", "member"); ``` LANGUAGE: ts CODE: ``` await redis.zrem("key", "member1", "member2"); ``` ---------------------------------------- TITLE: Configure Laravel Todo Model for Mass Assignment DESCRIPTION: Updates the `Todo` Eloquent model by adding 'title' to the `$fillable` array, enabling mass assignment. This is essential for creating or updating `Todo` records via API requests or forms in Laravel, preventing MassAssignmentException. SOURCE: https://upstash.com/docs/redis/tutorials/laravel_caching.mdx LANGUAGE: php CODE: ``` */ use HasFactory; protected $fillable = ['title']; } ``` ---------------------------------------- TITLE: Python ZUNIONSTORE with Aggregation DESCRIPTION: Illustrates how to use the ZUNIONSTORE command with the 'aggregate' option set to 'SUM' and 'withscores' enabled. This example shows how scores from common members are combined and returned as a list of (member, score) tuples. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/zset/zunionstore.mdx LANGUAGE: py CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunionstore(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` ---------------------------------------- TITLE: Configure Strapi Upstash Rate Limit Using IP Address DESCRIPTION: This JSON configuration enables the Strapi Upstash Rate Limit plugin and applies a fixed-window rate limit to all GET and POST routes. The rate limit identifies users by their IP address, allowing 10 tokens per 20-second window. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/integrations/strapi/configurations.mdx LANGUAGE: json CODE: ``` { "strapi-plugin-upstash-ratelimit": { "enabled": true, "resolve": "./src/plugins/strapi-plugin-upstash-ratelimit", "config": { "enabled": true, "token": "process.env.UPSTASH_REDIS_REST_TOKEN", "url": "process.env.UPSTASH_REDIS_REST_URL", "strategy": [ { "methods": ["GET", "POST"], "path": "*", "identifierSource": "ip", "limiter": { "algorithm": "fixed-window", "tokens": 10, "window": "20s" } } ], "prefix": "@strapi" } } } ``` ---------------------------------------- TITLE: Perform BITOP operation with TypeScript DESCRIPTION: Demonstrates how to use the `bitop` command with the Upstash Redis client in TypeScript, performing an AND operation between two source keys and storing the result in a destination key. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/bitmap/bitop.mdx LANGUAGE: TypeScript CODE: ``` await redis.bitop("AND", "destKey", "sourceKey1", "sourceKey2"); ``` ---------------------------------------- TITLE: Configure AWS SAM Template for Upstash Redis Environment Variables DESCRIPTION: Modifies the `template.yaml` file to define parameters for `UpstashRedisRestURL` and `UpstashRedisRestToken`, and passes these as environment variables to the `HelloWorldFunction` Lambda. This enables the Lambda function to securely access Upstash Redis credentials at runtime. SOURCE: https://upstash.com/docs/redis/tutorials/using_aws_sam.mdx LANGUAGE: yaml CODE: ``` AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > sam-app Sample SAM Template for sam-app Globals: Function: Timeout: 3 MemorySize: 128 Parameters: UpstashRedisRestURL: Type: String UpstashRedisRestToken: Type: String Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: CodeUri: hello_world/ Handler: app.lambda_handler Runtime: python3.9 Architectures: - x86_64 Events: HelloWorld: Type: Api Properties: Path: /hello Method: get Environment: Variables: UPSTASH_REDIS_REST_URL: !Ref UpstashRedisRestURL UPSTASH_REDIS_REST_TOKEN: !Ref UpstashRedisRestToken Outputs: HelloWorldApi: Description: "API Gateway endpoint URL for Prod stage for Hello World function" Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" HelloWorldFunction: Description: "Hello World Lambda Function ARN" Value: !GetAtt HelloWorldFunction.Arn HelloWorldFunctionIamRole: Description: "Implicit IAM Role created for Hello World function" Value: !GetAtt HelloWorldFunctionRole.Arn ``` ---------------------------------------- TITLE: Upstash Redis PTTL Usage in TypeScript DESCRIPTION: Demonstrates how to use the `pttl` method with the Upstash Redis client in TypeScript to retrieve the expiration time of a key in milliseconds. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/generic/pttl.mdx LANGUAGE: typescript CODE: ``` const millis = await redis.pttl(key); ``` ---------------------------------------- TITLE: TypeScript Example for JSON.OBJLEN Usage DESCRIPTION: A practical TypeScript code snippet demonstrating how to call the `json.objlen` method using the Upstash Redis client to retrieve the number of keys in a JSON object. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/json/objlen.mdx LANGUAGE: ts CODE: ``` const lengths = await redis.json.objlen("key", "$.path"); ``` ---------------------------------------- TITLE: TypeScript Example for HVALS Command DESCRIPTION: Demonstrates how to use the HVALS command with Upstash Redis in TypeScript, showing how to set hash fields and then retrieve all values from the hash. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/hash/hvals.mdx LANGUAGE: ts CODE: ``` await redis.hset("key", { field1: "Hello", field2: "World" }) const values = await redis.hvals("key") console.log(values) // ["Hello", "World"] ``` ---------------------------------------- TITLE: JSON Response for Redis Command Error DESCRIPTION: Examples of JSON responses from the Upstash REST API when a Redis command fails or is rejected, showing the `error` field with an explanatory message. SOURCE: https://upstash.com/docs/redis/features/restapi.mdx LANGUAGE: json CODE: ``` {"error":"WRONGPASS invalid password"} {"error":"ERR wrong number of arguments for 'get' command"} ``` ---------------------------------------- TITLE: TypeScript Example for LMOVE Redis Command DESCRIPTION: Demonstrates how to use the LMOVE command with the Upstash Redis client in TypeScript. It shows pushing elements to a source list and then moving an element from the left side of the source list to the left side of the destination list. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/list/lmove.mdx LANGUAGE: ts CODE: ``` await redis.rpush("source", "a", "b", "c"); const element = await redis.move("source", "destination", "left", "left"); ``` ---------------------------------------- TITLE: Resolve ReferenceError: fetch is not defined in Node.js DESCRIPTION: Addresses the 'ReferenceError: fetch is not defined' issue in Node.js environments (v17 and earlier) where `fetch` is not natively supported. It provides a solution by installing and importing `isomorphic-fetch` as a polyfill. SOURCE: https://upstash.com/docs/redis/sdks/ts/troubleshooting.mdx LANGUAGE: bash CODE: ``` npm i isomorphic-fetch ``` LANGUAGE: ts CODE: ``` import { Redis } from "@upstash/redis"; import "isomorphic-fetch"; const redis = new Redis({ /*...*/ }); ``` ---------------------------------------- TITLE: Run Serverless Redis HTTP (SRH) via Docker Command DESCRIPTION: This command starts an SRH container, mapping port 8080 to its internal port 80. It configures SRH to use environment variables for mode and token, and connects to a specified Redis server, ideal for quick local testing. SOURCE: https://upstash.com/docs/redis/sdks/ts/developing.mdx LANGUAGE: bash CODE: ``` docker run \ -it -d -p 8080:80 --name srh \ -e SRH_MODE=env \ -e SRH_TOKEN=your_token_here \ -e SRH_CONNECTION_STRING="redis://your_server_here:6379" \ hiett/serverless-redis-http:latest ``` ---------------------------------------- TITLE: Python Example for Setting Redis Key Expiry DESCRIPTION: Demonstrates how to use the `redis.expire()` method in Python to set a timeout on a Redis key. Examples include setting expiry with an integer number of seconds and a `datetime.timedelta` object, verifying key deletion after the timeout. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/expire.mdx LANGUAGE: python CODE: ``` # With seconds redis.set("mykey", "Hello") redis.expire("mykey", 5) assert redis.get("mykey") == "Hello" time.sleep(5) assert redis.get("mykey") is None # With a timedelta redis.set("mykey", "Hello") redis.expire("mykey", datetime.timedelta(seconds=5)) ``` ---------------------------------------- TITLE: Connect to Upstash Redis with Redisson and Perform Basic Operations DESCRIPTION: This Java code snippet demonstrates how to initialize the Redisson client, connect to an Upstash Redis instance using a password and endpoint, and perform a basic `put` and `get` operation on a distributed map (`RMap`). Remember to replace placeholders for password and endpoint, and use `rediss://` for SSL connections. SOURCE: https://upstash.com/docs/redis/tutorials/redisson.mdx LANGUAGE: Java CODE: ``` public class Main { public static void main(String[] args) { Config config = new Config(); config.useSingleServer().setPassword("YOUR_PASSWORD") // use "rediss://" for SSL connection .setAddress("YOUR_ENDPOINT"); RedissonClient redisson = Redisson.create(config); RMap map = redisson.getMap("map"); map.put("foo", "bar"); System.out.println(map.get("foo")); } } ``` ---------------------------------------- TITLE: Python EXPIREAT Usage Examples DESCRIPTION: Illustrates how to use the `expireat` method in Python. Examples include setting an expiration using a `datetime` object for a future time and using a Unix timestamp to specify the expiration. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/expireat.mdx LANGUAGE: python CODE: ``` # With a datetime object redis.set("mykey", "Hello") redis.expireat("mykey", datetime.datetime.now() + datetime.timedelta(seconds=5)) # With a unix timestamp redis.set("mykey", "Hello") redis.expireat("mykey", int(time.time()) + 5) ``` ---------------------------------------- TITLE: ZDIFFSTORE Command Usage in TypeScript DESCRIPTION: Demonstrates how to use the ZDIFFSTORE command with the Upstash Redis client in TypeScript to store the difference between two sorted sets into a new destination key. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/zset/zdiffstore.mdx LANGUAGE: ts CODE: ``` const values = await redis.zdiffstore("destination", 2, "key1", "key2"); ``` ---------------------------------------- TITLE: Python Bitfield Increment Operation Example DESCRIPTION: Shows how to increment multiple 4-bit unsigned integer values within a Redis bitfield using the `incr` command. The example initializes an empty key and then increments two distinct 4-bit segments, asserting the resulting values. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/bitmap/bitfield.mdx LANGUAGE: py CODE: ``` redis.set("mykey", "") # Increment offset 0 by 16, return # Increment offset 4 by 1 result = redis.bitfield("mykey") \ .incr("u4", 0, 16) \ .incr("u4", 4, 1) \ .execute() assert result == [0, 1] ``` ---------------------------------------- TITLE: TypeScript Example for JSON.FORGET DESCRIPTION: Illustrates how to call the `json.forget` method using a TypeScript Redis client, specifying the key and the JSON path to be deleted. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/json/forget.mdx LANGUAGE: ts CODE: ``` await redis.json.forget("key", "$.path.to.value"); ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables DESCRIPTION: Environment variables required to connect to the Upstash Redis database. These should be placed in a `.env` file and replaced with your actual Upstash Redis URL and token. SOURCE: https://upstash.com/docs/redis/tutorials/using_serverless_framework.mdx LANGUAGE: shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Python Example for GETSET Command DESCRIPTION: This Python example demonstrates how to use the `GETSET` command. It first sets a key with an 'old-value', then calls `getset` to replace it with 'newvalue' and asserts that the returned value is the original 'old-value'. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/string/getset.mdx LANGUAGE: py CODE: ``` redis.set("key", "old-value") assert redis.getset("key", "newvalue") == "old-value" ``` ---------------------------------------- TITLE: Configure Upstash Redis environment variables DESCRIPTION: Adds the Upstash Redis REST URL and Token to the project's `.env` file, making them accessible to the application. SOURCE: https://upstash.com/docs/redis/quickstarts/ion.mdx LANGUAGE: shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Set Multiple Fields with HSET (Python) DESCRIPTION: Illustrates how to set multiple fields and their values simultaneously in a Redis hash using the `hset` command in Python, by passing a dictionary of key-value pairs. The example asserts the total number of fields added. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/hash/hset.mdx LANGUAGE: python CODE: ``` assert redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) == 2 ``` ---------------------------------------- TITLE: Configure Strapi Upstash Rate Limit with Multiple Algorithms and Paths DESCRIPTION: This JSON configuration demonstrates how to apply different rate limiting strategies to specific routes. It uses a fixed-window algorithm for '/api/restaurants/:id' and a token bucket algorithm for '/api/restaurants', both identified by the 'x-author' header. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/integrations/strapi/configurations.mdx LANGUAGE: json CODE: ``` { "strapi-plugin-upstash-ratelimit": { "enabled": true, "resolve": "./src/plugins/strapi-plugin-upstash-ratelimit", "config": { "enabled": true, "token": "process.env.UPSTASH_REDIS_REST_TOKEN", "url": "process.env.UPSTASH_REDIS_REST_URL", "strategy": [ { "methods": ["GET", "POST"], "path": "/api/restaurants/:id", "identifierSource": "header.x-author", "limiter": { "algorithm": "fixed-window", "tokens": 10, "window": "20s" } }, { "methods": ["GET"], "path": "/api/restaurants", "identifierSource": "header.x-author", "limiter": { "algorithm": "tokenBucket", "tokens": 10, "window": "20s", "refillRate": 1 } } ], "prefix": "@strapi" } } } ``` ---------------------------------------- TITLE: Test and Deploy Cloudflare Worker DESCRIPTION: These commands are used for local development and deployment of your Cloudflare Worker. `npx wrangler dev` allows you to test your function locally, while `npx wrangler deploy` publishes your Worker to Cloudflare's global edge network. SOURCE: https://upstash.com/docs/redis/quickstarts/cloudflareworkers.mdx LANGUAGE: shell CODE: ``` npx wrangler dev ``` LANGUAGE: shell CODE: ``` npx wrangler deploy ``` ---------------------------------------- TITLE: API Documentation for JSON.GET Method DESCRIPTION: Comprehensive documentation for the JSON.GET method, outlining its required and optional parameters, their types, and the structure of the expected response. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/json/get.mdx LANGUAGE: APIDOC CODE: ``` Method: JSON.GET Description: Get a single value from a JSON document. Arguments: - key (str, required): The key of the json entry. - paths (*List[str], default=$): One or more paths to retrieve from the JSON document. Response: - List[TValue | null] (required): The value at the specified path or null if the path does not exist. ``` ---------------------------------------- TITLE: JSON.DEL API Reference DESCRIPTION: Documents the JSON.DEL command for deleting a key from a JSON document, including its arguments and expected response. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/json/del.mdx LANGUAGE: APIDOC CODE: ``` Command: JSON.DEL Description: Delete a key from a JSON document. Arguments: - name: key type: str required: true description: The key of the json entry. - name: path type: str default: $ description: The path to delete Response: - type: int required: true description: How many paths were deleted. ``` ---------------------------------------- TITLE: Histogram API Endpoints DESCRIPTION: Definition of the REST API endpoints for recording and retrieving histogram data. This includes details on methods, parameters, and expected responses for both the `/record` and `/get` endpoints. SOURCE: https://upstash.com/docs/redis/tutorials/histogram.mdx LANGUAGE: APIDOC CODE: ``` API Endpoints: /record: Method: POST Description: Records numeric values into the histogram. Request Body: name: string (required) - The name of the histogram. values: array (required) - An array of numeric values to record. Response: Success (200): message: "Success" name: string - The name of the histogram. Error (400): message: "Invalid parameters. Name and values are needed." /get: Method: GET Description: Returns the histogram object. Query Parameters: name: string (required) - The name of the histogram to retrieve. Response: Success (200): histogram: object - The generated histogram object. Error (400): message: "Invalid parameters. Name is needed." ``` ---------------------------------------- TITLE: JSON.TOGGLE API Documentation DESCRIPTION: Documents the `JSON.TOGGLE` command, including its required arguments (`key`, `path`) and the expected response type (List[boolean]). This command is used to toggle a boolean value at a specified JSON path within a Redis key. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/json/toggle.mdx LANGUAGE: APIDOC CODE: ``` JSON.TOGGLE: Arguments: key: type: str required: true description: The key of the json entry. path: type: str default: $ description: The path of the boolean. Response: type: List[boolean] required: true description: The new value of the boolean. ``` ---------------------------------------- TITLE: Python Example for JSON.STRAPPEND DESCRIPTION: Demonstrates how to use the `JSON.STRAPPEND` command with a Python Redis client, showing a typical invocation with example arguments. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/json/strappend.mdx LANGUAGE: python CODE: ``` redis.json.strappend("key", "$.path.to.str", "abc") ``` ---------------------------------------- TITLE: Python Example for EVAL_RO with Arguments DESCRIPTION: Shows how to use `eval_ro` in Python to execute a simple Lua script that returns an argument passed to it. This illustrates passing dynamic data to the Lua script via the `args` parameter. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/scripts/eval_ro.mdx LANGUAGE: python CODE: ``` assert redis.eval_ro("return ARGV[1]", args=["Hello"]) == "Hello" ``` ---------------------------------------- TITLE: EXPIRE Command API Reference DESCRIPTION: Detailed API documentation for the EXPIRE command, including its purpose, arguments, and expected boolean response indicating if the timeout was set. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/expire.mdx LANGUAGE: APIDOC CODE: ``` Command: EXPIRE Description: Sets a timeout on key. The key will automatically be deleted. Arguments: - key: str (required) Description: The key to set the timeout on. - seconds: int | datetime.timedelta (required) Description: The timeout in seconds as int or datetime.timedelta object - nx: bool (optional) Description: Set expiry only when the key has no expiry - xx: bool (optional) Description: Set expiry only when the key has an existing expiry - gt: bool (optional) Description: Set expiry only when the new expiry is greater than current one - lt: bool (optional) Description: Set expiry only when the new expiry is less than current one Response: - type: bool Description: True if the timeout was set ``` ---------------------------------------- TITLE: DEL Command API Documentation DESCRIPTION: Detailed API specification for the DEL command, including its required arguments and the expected response type and value. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/generic/del.mdx LANGUAGE: APIDOC CODE: ``` Command: DEL Description: Removes the specified keys. A key is ignored if it does not exist. Arguments: keys: *List[str] (required) Description: One or more keys to remove. Response: Type: int (required) Description: The number of keys that were removed. ``` ---------------------------------------- TITLE: Project Setup: Install Upstash Redis Package DESCRIPTION: Installs the official `@upstash/redis` client library, which is necessary for interacting with the Upstash Redis database from your application. SOURCE: https://upstash.com/docs/redis/quickstarts/sst-v2.mdx LANGUAGE: shell CODE: ``` npm install @upstash/redis ``` ---------------------------------------- TITLE: Upstash Redis Environment Variables Configuration DESCRIPTION: Defines the necessary environment variables (`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`) in the `.env` file to establish a connection to your Upstash Redis database. SOURCE: https://upstash.com/docs/redis/quickstarts/vercel-functions-pages-router.mdx LANGUAGE: shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables (.env) DESCRIPTION: This snippet illustrates the content of a `.env` file, which is used by the `python-dotenv` library to load Redis connection credentials, specifically `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`, into the application's environment at runtime. SOURCE: https://upstash.com/docs/redis/tutorials/python_url_shortener.mdx LANGUAGE: text CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables DESCRIPTION: Example `.env` file configuration for storing Upstash Redis connection details, including the REST URL and Token, which are essential for the application to connect to the database. SOURCE: https://upstash.com/docs/redis/quickstarts/vercel-functions-app-router.mdx LANGUAGE: shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables DESCRIPTION: This snippet shows how to set the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables in a `.env` file, which are necessary for connecting to an Upstash Redis database. SOURCE: https://upstash.com/docs/redis/tutorials/python_multithreading.mdx LANGUAGE: bash CODE: ``` UPSTASH_REDIS_REST_URL=your_upstash_redis_url UPSTASH_REDIS_REST_TOKEN=your_upstash_redis_token ``` ---------------------------------------- TITLE: Set Environment Variables for Local Next.js Project DESCRIPTION: Instructions for configuring `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` in a `.env.local` file for a local Next.js development environment. SOURCE: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted.mdx LANGUAGE: bash CODE: ``` UPSTASH_REDIS_REST_URL=**** UPSTASH_REDIS_REST_TOKEN=**** ``` ---------------------------------------- TITLE: Connect to Upstash Redis with @upstash/redis DESCRIPTION: This JavaScript code snippet demonstrates how to initialize the `@upstash/redis` client using a URL and token, and perform a simple `set` operation. It's typically used for quick testing or demonstration purposes. SOURCE: https://upstash.com/docs/redis/quickstarts/koyeb.mdx LANGUAGE: javascript CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ url: "", token: "", }); const data = await redis.set("foo", "bar"); ``` ---------------------------------------- TITLE: Handle Hashed Responses from Upstash Redis DESCRIPTION: Explains why `@upstash/redis` might return base64 encoded (hashed) responses by default to prevent deserialization issues. It demonstrates how to disable this behavior by setting `responseEncoding` to `false` in the Redis client options. SOURCE: https://upstash.com/docs/redis/sdks/ts/troubleshooting.mdx LANGUAGE: ts CODE: ``` await redis.set("key", "value"); const data = await redis.get("key"); console.log(data); // dmFsdWU= ``` LANGUAGE: ts CODE: ``` const redis = new Redis({ // ... responseEncoding: false, }); ``` ---------------------------------------- TITLE: TypeScript Example for JSON.MGET DESCRIPTION: Demonstrates how to use the `redis.json.mget` method in TypeScript to retrieve values from multiple JSON documents at a specified path. SOURCE: https://upstash.com/docs/redis/sdks/ts/commands/json/mget.mdx LANGUAGE: ts CODE: ``` const values = await redis.json.mget(["key1", "key2"], "$.path.to.somewhere"); ``` ---------------------------------------- TITLE: Deploy Cloudflare Worker DESCRIPTION: Builds and deploys the Cloudflare Worker application to the Cloudflare network using `npx wrangler deploy`, making it accessible globally. SOURCE: https://upstash.com/docs/redis/tutorials/cloudflare_workers_with_redis.mdx LANGUAGE: shell CODE: ``` npx wrangler deploy ``` ---------------------------------------- TITLE: Python XADD Basic Usage Example DESCRIPTION: Demonstrates how to use the XADD command in Python to append a new entry to a Redis stream. It shows adding a simple key-value pair with an auto-generated ID. SOURCE: https://upstash.com/docs/redis/sdks/py/commands/stream/xadd.mdx LANGUAGE: py CODE: ``` redis.xadd(key, "*", { name: "John Doe", age: 30 }) ``` ---------------------------------------- TITLE: Real-Time Chat Interface (HTML, CSS, JavaScript) DESCRIPTION: This HTML file (`chat.html`) provides the complete front-end for the real-time chat application. It includes the structural elements (HTML), visual styling (CSS) for the chat box, messages, and input controls, and client-side logic (JavaScript) to connect to the Socket.IO server, handle user input, send messages, and display incoming messages in real-time. SOURCE: https://upstash.com/docs/redis/tutorials/python_realtime_chat.mdx LANGUAGE: HTML CODE: ``` Real-Time Chat