Skip to content

refactor: rename middleware.ts to proxy.ts - #812

Merged
sweetmantech merged 4 commits into
mainfrom
chore/middleware-to-proxy
Aug 5, 2026
Merged

sweetmantech merged 4 commits into
mainfrom
chore/middleware-to-proxy

Conversation

@sweetmantech

@sweetmantech sweetmantech commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Part of recoupable/app#1929 (PR 8 of 8, the last one).

Stacked on #811. Retarget to main once that merges.

⚠️ This is the only PR in the fleet that touches a live payment path. Sequenced last deliberately. Verification below focuses on proving the x402 challenge is unchanged.

Why

Next 16 deprecated the middleware convention in favour of proxy, and next dev said so on every boot:

⚠ The "middleware" file convention is deprecated. Please use "proxy" instead.

What changed

1. Renamed the file and the exported binding (export const middleware → export const proxy).

Checked the coupling before trusting it: x402-next@0.7.3's paymentMiddleware returns a plain (request: NextRequest) => Promise<NextResponse> and nothing in the package keys off the file name or the export name — export const middleware = ... is just the Next convention as written in their docs. No file in this repo imported it either.

2. Dropped runtime: "nodejs" from the config export. This one only showed up by running it. Next rejects the file outright when it is present:

⨯ Route segment config is not allowed in Proxy file at "./proxy.ts".
  Proxy always runs on Node.js runtime.

Proxy is Node-only and not configurable, which is exactly what the old runtime: "nodejs" was asking for — so this is a deletion, not a behaviour change. matcher is untouched.

Verification

Locally on next dev:

Check Result
middleware deprecation warning ✅ gone
Route-segment-config error ✅ gone after dropping runtime
Proxy actually executing ✅ GET /api/artists 500 in 11.9s (… proxy.ts: 415ms …) — the request log names it
Unpaid GET /api/x402/image/generate ✅ 402 {"x402Version":1,"error":"X-PAYMENT header is required","accepts":[{"scheme":"exact","network":"base","maxAmountRequired":"150000",…}]}
pnpm build type check ✅ 0 errors
pnpm lint:check ✅ 0 errors, 2 pre-existing warnings
pnpm test ✅ 797 files / 4329 tests

The 500 on /api/artists is that route throwing STRIPE_SK environment variable is required in my shell — application code, reached through the proxy, which is the point.

The 402 payload matches the baseline captured on #811's preview before this rename: same price (150000 = $0.15 at USDC's 6 decimals), same network, same description. The paid path is byte-for-byte unchanged.

Before merging

I'd want the same 402 check re-run against this branch's own preview deployment, not just locally — the facilitator and SMART_ACCOUNT_ADDRESS differ by environment. Happy to run it once the preview is up; flagging rather than claiming it.

🤖 Generated with Claude Code


Summary by cubic

Renamed Next.js middleware to proxy to align with next@16 and removed the deprecated runtime config. Fixes the dev warning and keeps the x402 payment challenge unchanged.

  • Refactors
    • Renamed middleware.ts to proxy.ts and changed export from middleware to proxy.
    • Removed runtime: "nodejs" from config; matcher unchanged.
    • Verified: proxy runs in dev; unpaid GET /api/x402/image/generate returns the same 402; build, lint, and tests pass.

Written for commit b2da474. Summary will update on new commits.

Review in cubic

Bumps next 16.0.10 -> 16.3.0 and react/react-dom 19.2.1 -> 19.2.8.
16.3 brings Turbopack disk caching for `next build`, memory eviction in
dev, and native Node.js streams in the App Router render path.

Also drops `eslint-config-next` (15.1.7). It is a dead dependency here:
`eslint.config.js` builds its own flat config from @typescript-eslint,
prettier, jsdoc and import, and never references the Next config or
@next/eslint-plugin-next. Nothing but package.json mentioned it.

Commits the `<!-- BEGIN:nextjs-agent-rules -->` block that `next dev`
writes into AGENTS.md on 16.2+. It points agents at version-matched docs
in node_modules/next/dist/docs/, and `next dev` re-adds it on every run,
so committing it is what keeps the tree clean.

Tracked in recoupable/app#1929.
Next 16.3 switched the default type checker to the project-local `tsc`
CLI. Per the useTypeScriptCli docs it checks "the complete project
selected by the configured tsconfig file ... including test files", where
16.0's compiler-API checker narrowed the set to app code.

tsconfig.json is `"include": ["**/*.ts"]`, so every __tests__ file entered
the build's type check for the first time and 203 pre-existing fixture
errors failed the build and the preview deploy. They are not regressions:
on main with 16.0.10 reinstalled and a cold tsbuildinfo, `next build`
emits 0 error TS lines, and this bump introduces 0 new errors while fixing
33 of them.

Points the build at a tsconfig.build.json that excludes test files, so the
build checks what it checked before. This is scoping, not silencing --
`pnpm exec tsc --noEmit` still uses the root tsconfig and still reports
all 203, which is where the burn-down will happen.

Verified: build compiles and type-checks with 0 errors, then stops at
`STRIPE_SK environment variable is required` collecting page data, which
is the same point main reaches locally. tsc --noEmit still reports 203.
Tests 797/797 files, 4329/4329.
Next 16 deprecated the `middleware` file convention in favour of `proxy`,
and `next dev` said so on every boot:

    ⚠ The "middleware" file convention is deprecated.
      Please use "proxy" instead.

Renames the file and the exported binding. x402-next is unaffected:
paymentMiddleware returns a plain
`(request: NextRequest) => Promise<NextResponse>`, and nothing in the
package keys off the file name or the export name -- `export const
middleware = ...` is only the Next convention in their docs. No file in
this repo imported it either.

Also drops `runtime: "nodejs"` from the config export. Next rejects the
file outright with it present:

    ⨯ Route segment config is not allowed in Proxy file at "./proxy.ts".
      Proxy always runs on Node.js runtime.

Proxy is Node-only and not configurable, which is what we already wanted,
so this is a deletion rather than a behaviour change. `matcher` stays.

Verified locally on `next dev`: deprecation warning gone, no route-segment
error, `proxy.ts: 415ms` in the request log confirming it runs, and an
unpaid GET /api/x402/image/generate still returns the 402 challenge with
maxAmountRequired 150000. Build type check 0 errors, lint 0 errors, tests
797/797 files and 4329/4329.

Sequenced last in the fleet because it is the only change touching a live
payment path.

Tracked in recoupable/app#1929.
@cursor

cursor Bot commented Aug 4, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@vercel

vercel Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
api Ready Ready Preview Aug 5, 2026 4:38am

Request Review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • proxy.ts is excluded by none and included by none

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d5d76697-bb82-4af9-9213-d7f9de58e5c8

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@sweetmantech

Copy link
Copy Markdown
Contributor Author

Preview verification: ✅ green — paid path confirmed unchanged

This is the check I flagged as still pending in the PR body. Preview for chore/middleware-to-proxy: https://api-ggyhta59m-recoup.vercel.app

The x402 paid path

GET /api/x402/image/generate?prompt=test, unpaid → HTTP 402 with a full challenge. Field-by-field against the baseline captured on #811's preview before the rename:

Field #811 (as middleware.ts) #812 (as proxy.ts)
x402Version 1 1 ✅
error X-PAYMENT header is required same ✅
scheme / network exact / base exact / base ✅
maxAmountRequired 150000 150000 ✅
payTo — 0xbAf31935ED514e8F7da81D0A730AB5362DEEEEb7 ✅ matches SMART_ACCOUNT_ADDRESS
asset — 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 ✅ USDC on Base
description Generate an image from a text prompt using AI same ✅
outputSchema / queryParams present present ✅

150000 at USDC's 6 decimals is $0.15, matching IMAGE_GENERATE_PRICE. The payTo and asset addresses resolve against the preview environment's own facilitator config, which was the specific thing I wanted confirmed on a real deploy rather than locally.

The proxy still gates everything else

Check Expected Actual
GET /api/artists, no credentials 401 401 ✅
GET /api/definitely-not-a-route 404 404 ✅
CORS from next.config.ts headers() present access-control-allow-origin: * ✅

The matcher (/protected/:path*, /api/:path*) carried over intact through the rename, and dropping runtime: "nodejs" changed nothing observable — as expected, since proxy is Node-only by definition.

No secret or env value appears in any response. payTo and asset are public on-chain addresses that the x402 challenge is supposed to advertise.

All 8 PRs in recoupable/app#1929 are now open and verified.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 1 file

Confidence score: 4/5

  • In proxy.ts, the rename appears incomplete in checked-in setup/docs, so contributors may follow stale guidance and recreate a deprecated middleware.ts entrypoint, causing misconfigured Next.js 16 behavior and avoidable onboarding friction — update all setup instructions/templates to reference the proxy convention only.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="proxy.ts">

<violation number="1" location="proxy.ts:55">
P2: The rename leaves checked-in setup and contributor guidance pointing at the removed `middleware.ts` convention, so users following it will recreate the deprecated entrypoint instead of the Next.js 16 proxy and retain the invalid runtime config; update those examples and guidance to `proxy.ts`/`proxy` with matcher-only config.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread proxy.ts
};

export const middleware = paymentMiddleware(
export const proxy = paymentMiddleware(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The rename leaves checked-in setup and contributor guidance pointing at the removed middleware.ts convention, so users following it will recreate the deprecated entrypoint instead of the Next.js 16 proxy and retain the invalid runtime config; update those examples and guidance to proxy.ts/proxy with matcher-only config.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At proxy.ts, line 55:

<comment>The rename leaves checked-in setup and contributor guidance pointing at the removed `middleware.ts` convention, so users following it will recreate the deprecated entrypoint instead of the Next.js 16 proxy and retain the invalid runtime config; update those examples and guidance to `proxy.ts`/`proxy` with matcher-only config.</comment>

<file context>
@@ -52,7 +52,7 @@ const imageGenerateOutputSchema = {
 };
 
-export const middleware = paymentMiddleware(
+export const proxy = paymentMiddleware(
   SMART_ACCOUNT_ADDRESS,
   {
</file context>

@sweetmantech
sweetmantech changed the base branch from chore/next-16-3-upgrade to main August 5, 2026 04:36
@sweetmantech

Copy link
Copy Markdown
Contributor Author

Preview verification (re-run on current head): ✅ green

Re-verified after retargeting to main and merging origin/main — the head changed, so my earlier verification was against a stale commit and does not count for the merge decision.

Preview: https://api-gki32b1h4-recoup.vercel.app
Deployment sha: b2da474b — equal to this PR's head. MERGEABLE/CLEAN, diff is proxy.ts alone.

Production still runs middleware.ts, so this is a direct before/after on the same commit base.

The 402 payment challenge — field by field vs production

This is the whole risk of the PR, so I compared the full challenge rather than just the status code:

Field proxy.ts (preview) middleware.ts (prod)
x402Version 1 1 ✅
error X-PAYMENT header is required same ✅
scheme / network exact / base exact / base ✅
maxAmountRequired 150000 150000 ✅
payTo 0xbAf31935…DEEEEb7 same ✅
asset 0x833589fC…dA02913 same ✅
description Generate an image from a text prompt using AI same ✅
mimeType application/json application/json ✅
maxTimeoutSeconds 300 300 ✅
outputSchema 1560 chars 1560 chars ✅ byte-identical

Every field matches, including the full outputSchema. 150000 at USDC's 6 decimals is $0.15, matching IMAGE_GENERATE_PRICE. The payment contract is unchanged by the rename.

The proxy still gates everything it did as middleware

matcher is ["/protected/:path*", "/api/:path*"], and both arms behave:

Check Expected Actual
GET /api/artists, no credentials 401 401 "Exactly one of x-api-key or Authorization must be provided" ✅
GET /api/artists with a key minted on this preview 200 200 {"status":"success","artists":[]} ✅
GET /api/accounts/id 200 200, resolves the account ✅
GET /api/ai/models 200 200, full catalogue ✅
GET /api/artists with a bogus key 401 401 "Unauthorized" ✅
GET /api/not-a-real-route 404 404 ✅
/protected/anything matches prod 404 on both ✅
OPTIONS /api/artists preflight CORS headers all three access-control-allow-* present ✅

A prod key 401s against previews (different hash salt), so the key was minted on the preview itself via the unauthenticated agent-signup route.

Notes

  • runtime: "nodejs" had to be deleted, not carried over. Next rejects the file outright with it present: Route segment config is not allowed in Proxy file at "./proxy.ts". Proxy always runs on Node.js runtime. Since proxy is Node-only and non-configurable, that is exactly what the old key asked for — a deletion, not a behaviour change. This only surfaced by running it.
  • x402-next is unaffected by the rename. paymentMiddleware returns a plain (request: NextRequest) => Promise<NextResponse>; nothing in the package keys off the file name or export name, and no file in this repo imported it.
  • No secret or env value in any response header — only access-control-*, x-matched-path, x-robots-tag, and the workflow stream headers.
  • Test key and all response fixtures shredded from the scratchpad.

This is the last PR in the recoupable/app#1929 fleet. chat and marketing are both fully done.

@sweetmantech
sweetmantech merged commit 2e1dae2 into main Aug 5, 2026
4 checks passed

This branch was successfully deployed

1 active deployment
Preview — b2da474b Deployed Aug 5, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant