-
next build of the example with no USAGERAIL_APP_KEY set. The build skips SDK setup when the key is missing.
-
Placeholder app key, no UsageRail to reach: requests with no key or a malformed key both get a 401 before the handler runs.
-
lib/usagerail.js and one wrapped route handler from the example.
-
The Next.js setup guide.
Inspiration
I'm Super Lede, one of the three founders of UsageRail. We build API keys, rate limits, quotas and Stripe usage billing for small teams that sell an API. Our first SDK adapters were for long-running servers: Express, Hono and Fastify on Node.js, and FastAPI, Flask and Django on Python. There, a background loop sends usage counts every 60 seconds.
Some of the APIs we want to support are just route handlers in a Next.js app on Vercel. A serverless instance can be frozen between requests, so a background loop isn't an option there. This project is how we made the same checks and counts work in that setting.
What it does
It's the Next.js adapter in our open-source Node.js SDK (@usagerail/node/next), plus the example app we test it with. You wrap each route handler with rail.route(). Before your handler runs, it checks the customer's API key, their rate limit and their quota. Keys and limits come from a copy the SDK keeps in sync, so most requests are checked without a network call. An instance's first request, or one that finds the copy more than 20 seconds old, waits up to a second for a sync. A key that isn't in the copy yet is checked with UsageRail, and the first request from a customer on an instance may wait briefly for a quota lease. After the response goes out, the request is counted for that customer and route. Setup is in our guide to Next.js rate limit and API key checks.
The example has three routes:
GET /v1/items/[id]returns the item. The route template is what you give a weight to in the console.POST /v1/summariescounts 5 units withusage.track(5), for apps that bill by units rather than requests.GET /v1/brokenreturns a 500. Errors are recorded but not billed, and they don't use quota.
A request with no key, or with a key in the wrong format, gets a 401 before the handler runs. Over the rate limit, or over a quota that stops at the limit, it gets a 429. Two hours after a billing period ends, UsageRail sends the period's total to the seller's own Stripe account, which puts it on the customer's invoice.
How we built it
The SDK is TypeScript, published on npm and JSR as @usagerail/node. In Next.js it runs in what we call serverless mode: no background timer at all. After each response, after() from next/server sends the counts, picks up changes such as revoked keys or new limits, and renews quota leases.
- One instance sends a batch at most every 0.5 seconds. Requests that end in between go out with the next batch.
- A batch that fails stays in memory and goes out with the next request.
- A revoked key normally stops working within about 20 seconds, even on an instance that sat idle.
The example runs in our test suite next to the examples for the other frameworks. Each one is started against a real UsageRail API and checked for key checks, rate limits, quotas and the usage each request reports. For Next.js the test builds without an app key, then runs next start.
To see whether counts survive on Vercel, we deployed route handlers using the package from npm and ran three tests in October 2026: 60,000 requests at 100 a second, 120 requests a minute apart over two hours, and a burst of 70 requests at once that started 70 new instances.
Challenges we ran into
- Route templates. Next.js doesn't tell the handler which file it came from. With the raw path, every ID would become a route of its own. So
rail.route()takes the template as its first argument, written the way the folder is named:/v1/items/[id]. redirect()andnotFound()throw. We recognize them by the error's digest, record the real status (a 307 is billed, a 404 isn't), then rethrow so Next.js handles them as usual. Any other error is recorded as a 500.- Lost counts on shutdown. Running the example under
next startand stopping it showed that the last batches could disappear. The short waits in serverless mode used unref'd timers, as in the long-running mode. After SIGTERM closed the HTTP server, those timers were all that was left, so Node exited beforeafter()had finished. In serverless mode they're no longer unref'd. - Builds without secrets. The instance is created at module level and
next buildloads every route module, so builds failed withoutUSAGERAIL_APP_KEY. That breaks Docker builds that only get secrets at run time. Now the build skips setup when there's no key, and a missing key still throws at run time. - Rate limits across instances. Vercel runs as many instances as traffic needs, and each one counts rate limits on its own. With the default setting a customer can get the full limit on every instance, so the docs point to the "Split the limit across servers" setting.
Accomplishments that we're proud of
- In all three Vercel tests, every successful response was counted.
- The check is cheap because it runs in your process. In our Node.js benchmark on a 2-vCPU server (October 28, 2026), the SDK added under 20 µs per request at p99.
- The SDK doesn't send request or response bodies to UsageRail. It reports usage totals by customer and route.
What we learned
- On serverless, anything that happens "later" has to belong to a request. Every timer in this mode now lives inside a request or an
after()task. - The shutdown bug didn't show up in unit tests. It showed up when we ran the actual example the way people deploy it, and stopped it.
- Next.js uses thrown errors for normal control flow, so a wrapper has to read an error before deciding it's a failure.
What's next
Known gaps right now:
- Only the Node.js runtime is supported, which is the default for route handlers. The SDK uses
node:crypto, which the Edge runtime doesn't have. - Paths without a handler get Next.js's own 404 before UsageRail sees them, so they don't appear in analytics.
- The example app lives in our main repository. The SDK source, Next.js adapter included, is public in the usagerail/sdk repository on GitHub.
If you sell an API from Next.js, the free plan covers billing up to $1,000 a month. More on how we handle usage-based billing for APIs is on our site.
Built With
- hono
- javascript
- next.js
- node.js
- postgresql
- stripe
- typescript
- vercel