Skip to main content

Upstash Redis in Google Cloud Functions

note

This tutorial uses @upstash/redis which is designed for serverless runtimes for efficient connection handling. You can use your favorite Redis client, but you may have to deal with connection issues as described here.

Database Setup

Create a Redis database using Upstash Console or Upstash CLI. Select the GCP US-Central-1 as the region. Copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN for the next steps.

Project Setup

Create a folder for your project, then run npm init inside. Then install Upstash client with: npm install @upstash/redis

The Code

Update index.js as below:

const { Redis } = require("@upstash/redis/with-fetch");

const redis = new Redis({
url: 'UPSTASH_REDIS_REST_URL',
token: 'UPSTASH_REDIS_REST_TOKEN',
})

exports.helloCounter = async(req, res) => {
let count = await redis.incr("counter");
res.send('Page view:' + count);
};

Run and Deploy

Deploy your function to Google Cloud with:

gcloud functions deploy helloCounter \
--runtime nodejs16 --trigger-http --allow-unauthenticated

You will see the URL of your Cloud Function. Click to the URL to check if it is working properly.

httpsTrigger:
securityLevel: SECURE_OPTIONAL
url: https://us-central1-functions-317005.cloudfunctions.net/helloCounter

In case of an issue, you can check the logs of your Cloud Function in the GCP console as below.