Skip to content

Commit

Permalink
Add pages router test to nextjs example (#128)
Browse files Browse the repository at this point in the history
* feat: add pages router example

* feat: add test and rename

* fix: typo

---------

Co-authored-by: CahidArda <[email protected]>
  • Loading branch information
ytkimirti and CahidArda authored Oct 25, 2024
1 parent c667b63 commit f8529d2
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions examples/nextjs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ The `redis` parameter denotes the Upstash Redis instance we use. The `limiter` p

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.

There is also a pages router example in `pages/api/limit.ts`.

# Run locally

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
Expand Down
10 changes: 10 additions & 0 deletions examples/nextjs/ci.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ test("the server is running", async () => {
console.log(`${deploymentURL}/api`);
const res = await fetch(`${deploymentURL}/api`);

if (res.status !== 200) {
console.log(await res.text());
}
expect(res.status).toEqual(200);
}, { timeout: 10000 });

test("the pages router example is working", async () => {
console.log(`${deploymentURL}/api/pages-test`);
const res = await fetch(`${deploymentURL}/api/pages-test`);

if (res.status !== 200) {
console.log(await res.text());
}
Expand Down
33 changes: 33 additions & 0 deletions examples/nextjs/pages/api/pages-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { NextApiRequest, NextApiResponse } from "next";

import { waitUntil } from '@vercel/functions';
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
})

const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(10, "10 s"),
prefix: "@upstash/ratelimit",
analytics: true
});

export default async function handler(_req: NextApiRequest, res: NextApiResponse) {
const identifier = "pages-api";
const { success, limit, remaining, pending } = await ratelimit.limit(identifier);
const response = {
success: success,
limit: limit,
remaining: remaining
}

// pending is a promise for handling the analytics submission
waitUntil(pending)

res.status(success ? 200 : 429).json(response);

}

0 comments on commit f8529d2

Please sign in to comment.