GitHub Repository

You can find the project source code on GitHub.

Prerequisites

You need to have AWS credentials configured locally.

  1. Create an AWS account
  2. Create an IAM user
  3. Configure the AWS CLI

Project Setup

Let’s create a new SST + Next.js application.

npx create-sst@latest --template standard/nextjs
cd my-sst-app
npm install

Install the @upstash/redis package.

npm install @upstash/redis

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.

npx sst secrets set UPSTASH_REDIS_REST_URL <YOUR_URL>
npx sst secrets set UPSTASH_REDIS_REST_TOKEN <YOUR_TOKEN>

Bind the Secrets

/stacks/Default.ts
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,
  });
}

API Setup

/packages/web/pages/api/hello.ts
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 });
}

Run

Run the SST app.

npm run dev

After prompted, run the Next.js app.

cd packages/web
npm run dev

Check http://localhost:3000/api/hello

Deploy

Set the secrets for the prod stage.

npx sst secrets set --stage prod UPSTASH_REDIS_REST_URL <YOUR_URL>
npx sst secrets set --stage prod UPSTASH_REDIS_REST_TOKEN <YOUR_TOKEN>

Deploy with SST.

npx sst deploy --stage prod

Check <SiteUrl>/api/hello with the given SiteUrl.