Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Ruby on Rails CORS Preflight Check
before_action :cors_set_access_control_headers
def cors_preflight_check
return unless request.method == 'OPTIONS'
render json: {}
def cors_set_access_control_headers
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, PATCH, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token, ' \
'Auth-Token, Email, X-User-Token, X-User-Email, x-xsrf-token'
response.headers['Access-Control-Max-Age'] = '1728000'
response.headers['Access-Control-Allow-Credentials'] = true
match '*all', controller: 'application', action: 'cors_preflight_check', via: [:options]

This comment has been minimized.

Copy link

betocattani commented Nov 23, 2018

Nice my friend, thanks!


This comment has been minimized.

Copy link

dipunj commented Aug 28, 2019

This is just so helpful. Thanks a lot man!


This comment has been minimized.

Copy link

danielpowell4 commented Oct 31, 2019

Per rails/rails#12374 render :text is deprecated

So for my use, which is a tad different than this gist, which I was rather thankful for

before_action :whitelist_cors

def whitelist_cors
  response.headers['Access-Control-Allow-Origin'] = allow_origin_header
  response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
  response.headers['Access-Control-Allow-Headers'] = 'origin, content-type, accept'
  return render plain: '' if cors_preflight_check?

def cors_preflight_check?
  request.request_method == 'OPTIONS'

def allow_origin_header
  if public?
    # whitelist request.headers['origin'] or error

This comment has been minimized.

Copy link
Owner Author

jpbalarini commented Dec 19, 2019

@danielpowell4 updated the gist to remove the deprecated render :text. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.