Setting up Cloudflare Workers URL Parameters

Cloudflare workers are really awesome when you want to secure your API Endpoint. But most of the code available online can only process single URL Parameter.

But this will be bottleneck when you want to use more than one parameter.

Here is the code for using dual parameter.

addEventListener('fetch', event => {
async function fetchAndApply(request) {
    const init = {
      method: 'GET'
    const  { searchParams } = new URL(request.url);
    let param1 = searchParams.get('param1');
    let param2 = searchParams.get('param2');
    const [output] = await Promise.all([
      fetch('https://SITE-URL/app.php?param1=' + param1 + '&param2=' + param2 , init)
    const btsc = await output.json()
    const responseInit = {
      headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'GET',
          'Access-Control-Allow-Headers': 'Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With',
          'x-content-type-options': 'nosniff',
          'x-xss-protection': '1; mode=block',
          'x-frame-options': 'DENY'
    return new Response(JSON.stringify(btsc), responseInit)

You can easily extend this code to work with Multiple parameters

You can modify the parameter name in Line 9,10 and 12 with the respective names.

Advantages of using cloudflare workers.

  • Block Bots and Unusual traffic
  • Save Server Resources
  • Hide API URL
  • and many more

Leave a Comment