From 1ee5266ce9a3e3bf661429e6bd6f5bddc1536664 Mon Sep 17 00:00:00 2001 From: capJavert Date: Mon, 25 Nov 2024 21:48:43 +0100 Subject: [PATCH] feat: override traffic to cf --- packages/webapp/middleware.ts | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 packages/webapp/middleware.ts diff --git a/packages/webapp/middleware.ts b/packages/webapp/middleware.ts new file mode 100644 index 0000000000..45f1d9c1d8 --- /dev/null +++ b/packages/webapp/middleware.ts @@ -0,0 +1,48 @@ +import { NextRequest, NextResponse } from 'next/server'; + +const trafficPercentage = 10; + +const cfCookieName = 'cf-override'; + +const isDev = process.env.NODE_ENV !== 'production'; + +const middleware = async (req: NextRequest): Promise => { + let cfCookie = req.cookies.get(cfCookieName)?.value; + + const nextResponse = NextResponse.next(); + + if (typeof cfCookie === 'undefined') { + const shouldOverride = Math.random() < trafficPercentage / 100; + + nextResponse.cookies.set(cfCookieName, shouldOverride ? 'true' : 'false', { + path: '/', + maxAge: 1 * 60 * 60, + secure: !isDev, + httpOnly: true, + }); + + cfCookie = 'true'; + } + + if (cfCookie === 'true') { + const cfUrl = new URL( + `${req.nextUrl.pathname}${req.nextUrl.search}`, + process.env.CF_OVERRIDE_URL, + ); + + if (!isDev) { + return NextResponse.rewrite(cfUrl, nextResponse); + } + } + + return nextResponse; +}; + +export const config = { + matcher: [ + '/((?!api|_next/static|_next/image|favicon|manifest.json|robots.txt|android-chrome).*)', + '/', + ], +}; + +export { middleware };