Use this file to discover all available pages before exploring further.
GitHub Repository
You can find the project source code on GitHub.
This tutorial showcases using Redis with REST API in Cloudflare Workers. We will
write a sample edge function (Cloudflare Workers) which will show a custom
greeting depending on the location of the client. We will load the greeting
message from Redis so you can update it without touching the code.
Create a Cloudflare Worker with the following options:
➜ tutorials > ✗ npx wrangler init╭ Create an application with Cloudflare Step 1 of 3│├ In which directory do you want to create your application?│ dir ./greetings-cloudflare│├ What would you like to start with?│ category Hello World example│├ Which template would you like to use?│ type Hello World Worker│├ Which language do you want to use?│ lang TypeScript│├ Copying template files│ files copied to project directory│├ Updating name in `package.json`│ updated `package.json`│├ Installing dependencies│ installed via `npm install`│╰ Application created╭ Configuring your application for Cloudflare Step 2 of 3│├ Installing @cloudflare/workers-types│ installed via npm│├ Adding latest types to `tsconfig.json`│ added @cloudflare/workers-types/2023-07-01│├ Retrieving current workerd compatibility date│ compatibility date 2024-10-22│├ Do you want to use git for version control?│ no git│╰ Application configured
Create a Redis database using Upstash Console or Upstash CLI and copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN into your wrangler.toml file.
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<string>(country); if (greeting) { return new Response(greeting); } } return new Response('Hello!'); },};
The code tries to find out the user’s location checking the “cf-ipcountry”
header. Then it loads the corresponding greeting for that location using the Redis
REST API.