Skip to content

Commit

Permalink
feat: override traffic to cf
Browse files Browse the repository at this point in the history
  • Loading branch information
capJavert committed Nov 25, 2024
1 parent 32ecc3b commit 9c5f330
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions packages/webapp/middleware.ts
Original file line number Diff line number Diff line change
@@ -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<NextResponse> => {
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}`,
'https://cf.daily.dev',
);

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 };

0 comments on commit 9c5f330

Please sign in to comment.