GitHub Repository

You can find the project source code on GitHub.

This tutorial implements a serverless application and deploys it to AWS Lambda using Serverless Framework

Prerequisites

  1. Install the Serverless Framework with npm i serverless -g

Project Setup

Create a Serverless Framework application with the following options:

➜  tutorials > ✗ serverless
Serverless ϟ Framework

Welcome to Serverless Framework V.4

Create a new project by selecting a Template to generate scaffolding for a specific use-case.

✔ Select A Template: · AWS / Node.js / HTTP API

✔ Name Your Project: · counter-serverless

✔ Template Downloaded

✔ Create Or Select An Existing App: · Create A New App

✔ Name Your New App: · counter-serverless

Your new Service "counter-serverless" is ready. Here are next steps:

• Open Service Directory: cd counter-serverless
• Install Dependencies: npm install (or use another package manager)
• Deploy Your Service: serverless deploy
cd counter-serverless

Create package.json with @upstash/redis as a dependency:

package.json
{
    "dependencies": {
      "@upstash/redis": "latest"
    }
  }

Install the dependencies:

npm install

Database Setup

Create a Redis database using Upstash Console or Upstash CLI and copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN into your .env file.

.env
UPSTASH_REDIS_REST_URL=<YOUR_URL>
UPSTASH_REDIS_REST_TOKEN=<YOUR_TOKEN>

Counter Function Setup

Update handler.js:

handler.js
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),
    };
};

Update serverless.yml to pass the environment variables:

serverless.yml
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

Developing

Run the following command to start your dev session.

serverless dev

Deployment

Run the following command to deploy your service.

serverless deploy

Visit the output url.