Skip to content

Commit f8529d2

Browse files
ytkimirtiCahidArda
andauthored
Add pages router test to nextjs example (#128)
* feat: add pages router example * feat: add test and rename * fix: typo --------- Co-authored-by: CahidArda <[email protected]>
1 parent c667b63 commit f8529d2

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

examples/nextjs/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ The `redis` parameter denotes the Upstash Redis instance we use. The `limiter` p
4545

4646
To limit the requests, we call `ratelimit.limit` method with an identifier `"api"`. This identifier could be the ip address or the user id in your use case. See [our documentation](https://upstash.com/docs/oss/sdks/ts/ratelimit/methods#limit) for more information.
4747

48+
There is also a pages router example in `pages/api/limit.ts`.
49+
4850
# Run locally
4951

5052
To run the example in your local environment, create a Upstash Redis and set the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables. Then run

examples/nextjs/ci.test.ts

+10
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@ test("the server is running", async () => {
99
console.log(`${deploymentURL}/api`);
1010
const res = await fetch(`${deploymentURL}/api`);
1111

12+
if (res.status !== 200) {
13+
console.log(await res.text());
14+
}
15+
expect(res.status).toEqual(200);
16+
}, { timeout: 10000 });
17+
18+
test("the pages router example is working", async () => {
19+
console.log(`${deploymentURL}/api/pages-test`);
20+
const res = await fetch(`${deploymentURL}/api/pages-test`);
21+
1222
if (res.status !== 200) {
1323
console.log(await res.text());
1424
}
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { NextApiRequest, NextApiResponse } from "next";
2+
3+
import { waitUntil } from '@vercel/functions';
4+
import { Ratelimit } from "@upstash/ratelimit";
5+
import { Redis } from "@upstash/redis";
6+
7+
const redis = new Redis({
8+
url: process.env.UPSTASH_REDIS_REST_URL!,
9+
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
10+
})
11+
12+
const ratelimit = new Ratelimit({
13+
redis,
14+
limiter: Ratelimit.slidingWindow(10, "10 s"),
15+
prefix: "@upstash/ratelimit",
16+
analytics: true
17+
});
18+
19+
export default async function handler(_req: NextApiRequest, res: NextApiResponse) {
20+
const identifier = "pages-api";
21+
const { success, limit, remaining, pending } = await ratelimit.limit(identifier);
22+
const response = {
23+
success: success,
24+
limit: limit,
25+
remaining: remaining
26+
}
27+
28+
// pending is a promise for handling the analytics submission
29+
waitUntil(pending)
30+
31+
res.status(success ? 200 : 429).json(response);
32+
33+
}

0 commit comments

Comments
 (0)