x402 icon indicating copy to clipboard operation
x402 copied to clipboard

Allowing a function as `routeConfig` in `withX402`

Open yssf-io opened this issue 1 month ago • 3 comments

Description

This PR introduces a way to dynamically provide a routeConfig argument based on the NextRequest and whatever else the developer might need by making the routeConfig parameter of withX402 either a RouteConfig type or a (req: NextRequest) => Promise<RouteConfig> function.

Developers can now pass a function that will construct the right routeConfig according to any custom logic, like dynamic pricing based on the user making the request or based on the specific resource being bought.

Closes #608.

Tests

After making these changes, I tried protecting a NextJS endpoint with withX402 using both the static config (what the package currently offers) and using a function that fetches the price from a DB depending on what's in the request's body and returns a routeConfig object using that price.

Checklist

  • [x] I have formatted and linted my code
  • [x] All new and existing tests pass
  • [x] My commits are signed (required for merge) -- you may need to rebase if you initially pushed unsigned commits

yssf-io avatar Nov 25 '25 20:11 yssf-io

✅ Heimdall Review Status

Requirement Status More Info
Reviews 1/1
Denominator calculation
Show calculation
1 if user is bot 0
1 if user is external 0
2 if repo is sensitive 0
From .codeflow.yml 1
Additional review requirements
Show calculation
Max 0
0
From CODEOWNERS 0
Global minimum 0
Max 1
1
1 if commit is unverified 0
Sum 1

cb-heimdall avatar Nov 25 '25 20:11 cb-heimdall

@yssf-io is attempting to deploy a commit to the Coinbase Team on Vercel.

A member of the Team first needs to authorize it.

vercel[bot] avatar Nov 25 '25 20:11 vercel[bot]

Thanks for your contribution @yssf-io, looks good to me!

@CarsonRoscoe I succesfully tested this with the following modification to the example/next api/weather route:

export const GET = withX402(
  handler,
  payTo,
  async (request: NextRequest) => {
    const tier = request.nextUrl.searchParams.get("tier");
    const price = tier === "premium" ? "$0.005" : "$0.001";
    return {
      price,
      network,
      config: {
        description: "Access to weather API",
      },
    };
  },
  {
    url: facilitatorUrl,
  },
  {
    appName: "Next x402 Demo",
    appLogo: "/x402-icon-blue.png",
  },
);

phdargen avatar Nov 26 '25 13:11 phdargen