MCPcopy Create free account
hub / github.com/cloudflare/templates / createProtectedRoute

Function createProtectedRoute

x402-proxy-template/src/auth.ts:78–110  ·  view source on GitHub ↗
(config: ProtectedRouteConfig)

Source from the content-addressed store, hash-verified

76 * @returns Middleware that enforces payment or cookie authentication
77 */
78export function createProtectedRoute(config: ProtectedRouteConfig) {
79 return async (c: Context<AppContext>, next: Next) => {
80 // Get the route path from the request context
81 // Normalize the path by removing trailing slashes (except for root "/")
82 // This matches how x402's findMatchingRoute normalizes incoming request paths
83 const rawPath = c.req.path;
84 const routePath =
85 rawPath.length > 1 ? rawPath.replace(/\/+$/, "") : rawPath;
86
87 // Create payment middleware dynamically with config from env
88 // Facilitator is optional - x402 uses its own default when not provided
89 const facilitator = c.env.FACILITATOR_URL
90 ? { url: c.env.FACILITATOR_URL }
91 : undefined;
92
93 const paymentMw = paymentMiddleware(
94 c.env.PAY_TO as `0x${string}`,
95 {
96 [routePath]: {
97 price: config.price,
98 network: c.env.NETWORK,
99 config: {
100 description: config.description,
101 },
102 },
103 },
104 facilitator
105 );
106
107 // Apply the combined auth/payment middleware
108 return await requirePaymentOrCookie(paymentMw)(c, next);
109 };
110}

Callers 1

index.tsFile · 0.90

Calls 2

requirePaymentOrCookieFunction · 0.85
replaceMethod · 0.65

Tested by

no test coverage detected