Firebase functions and CORS

A simple firebase http function template:

// accessible at https://us-central1-<app name>.cloudfunctions.net/testEndpoint
exports.testEndpoint = functions.https.onRequest(req, res) => {
  if (cors(req, res)) {
    res.end()
    return
  }

  // do something

  // make sure to 'end' the request or it'll time out
  res.send(true)
  res.end()
})

We need to handle CORS requests (see cors() above), because the browser will send an OPTIONS request first to see what’s accepted by the endpoint. Your function handler in this case will receive an empty body, throw a bunch of errors, and generally waste a ton of time.

A simple CORS handler template:

const cors = (req, res) => {
  const ALLOWED_ORIGINS = [
    'http://localhost:3000',
    'https://app.domain.com'
  ]

  if (ALLOWED_ORIGINS.includes(req.headers.origin)) {
    res.set('Access-Control-Allow-Origin', req.headers.origin)
    res.set('Access-Control-Allow-Headers', '*')
  }

  if (req.method === 'OPTIONS') {
    res.end()
    return true
  }
  return false
}

If it’s an OPTIONS request, send back the approved origin and end the response (via true response).

If it’s a different type of request, set the approved origin and continue (via false response).