Recently, the 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 great news if you need low latency all over the world.
In this article, I will create a basic API that will count the page views for each edge location. I will use Upstash Global Redis to keep the page counts. Because Upstash replicates the data to multiple regions, it helps 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
- Create a Global Redis database on Upstash and copy the REST URL and token.
The Code
Update the
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.