Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: override traffic to cf #3879

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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> => {
capJavert marked this conversation as resolved.
Show resolved Hide resolved
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,
Comment on lines +18 to +21
Copy link
Contributor Author

Choose a reason for hiding this comment

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

sets the override for the next 1 hour

});

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).*)',
Copy link
Contributor Author

@capJavert capJavert Nov 26, 2024

Choose a reason for hiding this comment

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

do not override static stuff because they would be requested from cf.daily.dev either way when main document is loaded

'/',
],
};

export { middleware };