Skip to content

feedback: Cloudflare worker proxy #23

@BrentOnRails

Description

@BrentOnRails

If you're interested, I ended up implementing this via Cloudflare workers using this nginx config as inspiration.

  1. Create a worker and add the javascript
export default {
	async fetch(request) {
		return handleRequest(request)
	}
}

async function handleRequest(request) {
	const url = new URL(request.url)
	let targetUrl

	// Determine the target URL based on the request path
	switch (true) {
		case url.pathname === '/lib.min.js':
			targetUrl = 'https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js';
			break;
		case url.pathname === '/lib.js':
			targetUrl = 'https://cdn.mxpnl.com/libs/mixpanel-2-latest.js';
			break;
		case url.pathname.startsWith('/decide'):
			targetUrl = 'https://decide.mixpanel.com' + url.pathname.slice('/decide'.length);
			break;
		default:
			targetUrl = 'https://api.mixpanel.com' + url.pathname;
			break;
	}

	// Create a new request with the target URL and the original request's settings
	const modifiedRequest = new Request(targetUrl, {
		method: request.method,
		headers: request.headers,
		body: request.body,
		redirect: request.redirect,
	})

	// Add necessary headers to mimic the Nginx configuration
	modifiedRequest.headers.set('X-Real-IP', request.headers.get('cf-connecting-ip'))
	modifiedRequest.headers.set('X-Forwarded-For', request.headers.get('cf-connecting-ip'))
	modifiedRequest.headers.set('X-Forwarded-Host', url.hostname)

	// Fetch the modified request
	const response = await fetch(modifiedRequest)

	return response
}
  1. set the route you want in settings -> triggers -> custom domains

Cloudflare workers also support the one button deployment badges

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions