Tutorials
Using Serverless Framework
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
- Install the Serverless Framework with
npm i serverless -g
Project Setup
Create a Serverless Framework application with the following options:
➜ tutorials > ✗ serverlessServerless ϟ FrameworkWelcome to Serverless Framework V.4Create 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-serverlessYour 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 deploycd counter-serverlessCreate package.json with @upstash/redis as a dependency:
package.json
{ "dependencies": { "@upstash/redis": "latest" } }Install the dependencies:
npm installDatabase 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-serverlessprovider: 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: getDeveloping
Run the following command to start your dev session.
serverless devDeployment
Run the following command to deploy your service.
serverless deployVisit the output url.