CORS not supported

I’m trying to create a worker which updates my Algolia index when I send a request to my worker. The algoliasearch library works in both the browser and Node.js but it seems to be throwing errors inside the Cloudflare Workers environment.

const algoliasearch = require('algoliasearch')

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function fetchPlugins() {
  const response = await fetch('https://poggit.pmmp.io/plugins.json')
  const json = await response.json()
  return json
}

/**
 * Create plugins index
 */
function createIndex() {
  return new Promise((resolve, reject) => {
    const algoliaClient = algoliasearch('XI77W278IB', '91f72a0cbdcb942942d3d6e65364f47f');
    const algoliaIndex = algoliaClient.initIndex('prod_POGGIT_SEARCH');
    algoliaIndex.setSettings({
      searchableAttributes: ['name', 'version', 'keywords', 'tagline'],
      customRanking: ['desc(downloads)'],
      attributesForFaceting: [],
      attributesToSnippet: ['name', 'tagline'],
      attributesToHighlight: ['name', 'tagline'],
      attributeForDistinct: 'name',
      distinct: true,
      hitsPerPage: 5
    }, (err) => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })
}

/**
 * Index plugins
 */
function indexPlugins(plugins) {
  return new Promise((resolve, reject) => {
    const algoliaClient = algoliasearch('ALGOLIA_APP_ID, 'ALGOLIA_API_KEY');
    const algoliaIndex = algoliaClient.initIndex('ALGOLIA_INDEX_NAME');

    // loop through the plugins and add to a records array
    var records = []
    for (var i = 0; i < plugins.length; i++) { 
      var plugin = plugins[i];
      records.push(Object.assign({}, plugin))
    }

    // clear old records from index
    algoliaIndex.clearIndex((err) => {
      if (err) {
        reject(err)
      } else {
        // then add all the objects in one batch call
        algoliaIndex.addObjects(records, (err) => {
          if (err) {
            reject(err)
          } else {
            resolve()
          }
        });
      }
    })
  })
}

/**
 * Fetch and log a request
 * @param {Request} request
 */
async function handleRequest(request) {
  try {
    const plugins = await fetchPlugins()
    await createIndex()
    // await indexPlugins(plugins)
  } catch (err) {
    console.log(err)
    return new Response(JSON.stringify({
      success: false,
      message: err.message
    }), { status: 500 })
  }
}

Hi @fna371858,

The Cloudflare Workers implementation of the Fetch specification does not implement CORS, because it doesn’t make much sense on the edge. That said, it’d be nice if browser libraries just worked out of the box on the Workers platform. We’d have to take a look at Algolia’s library and see how it uses the Fetch API to see if there’s a way we could support it.

Harris

2 Likes

I had a look through their library and the error seems to be coming from https://github.com/algolia/algoliasearch-client-javascript/blob/9a3fcdc20aeaebf7ab3eccf7bcb8bbfe3f8b636c/src/browser/createAlgoliasearch.js#L64-L67

Oof, so they’re not using Fetch at all, they’re using XHR. I don’t think we’ll ever support XHR, I’m sad to say, so I think that library is simply incompatible with Cloudflare Workers.