·2 min read

Next.js Edge API Routes and Serverless Redis on Vercel

Noah FischerNoah FischerDevRel @Upstash

Recently, Next.js team has announced Next 12.2. The most exciting news for me is the Edge API Routes. Edge API Routes enable developers to run their APIs at edge locations. This is a great news if you need low latency all over the world.

In this article, I will create a basic API which will count the page views per each edge location. I will use Upstash Global Redis to keep the page counts. Because Upstash replicates the data to multiple regions, it helps to keep the latency low. I will deploy the Next.js application to Vercel which supports the Edge runtime.

Project Setup

  • Create the project: npx create-next-app@latest --typescript

  • Install Upstash Redis client: npm install @upstash/redis

You can use any Redis client, but we recommend @upstash/redis
  • Create a Global Redis database on Upstash and copy the REST URL and token.

The Code

Update the

pages/api/hello.ts
import type { NextRequest } from "next/server";
import { Redis } from "@upstash/redis";
 
const redis = new Redis({
  url: "REPLACE_YOUR_REST_URL",
  token: "REPLACE_YOUR_TOKEN",
});
 
export default async (req: NextRequest) => {
  let loc = req.geo?.country || "World";
  const count = await redis.incr(loc);
  return new Response(`Location: ${loc}  View count: ${count}`);
};
 
export const config = {
  runtime: "experimental-edge",
};

Deploy

Run vercel --prod to deploy your application. Test the URL from different locations (you may use a VPN). You should see different view counts for each location.