User sign-in from SPA to Rails backend


Nowadays it is popular to create fullstack-JS applications (meaning both front- and backend written in Javascript) but what if you want to use the vastly more productive environment of Rails for the backend, and keep the JS frontend?

This article tries to sort out the common snags you can run in to.

There are basically a few areas that cause immediate confusion

  1. Authentication, where its VERY common to use Devise on the Rails end
  2. CSRF Protection, Cross-site Request Forgery Protection where Rails has a good default technique where you pass on a secret token generated by the server. However you must mimic this technique in JS.
  3. CORS, Cross-Origin Resource Sharing, a generic technique used by browsers where they deny an app in the domain “” to access scripts in the domain “”.

3 is applicable because if the SPA page is served from another port than the backend API, it is considered to be another domain, and thereby unsafe. So even if your Rails app runs on localhost:3000 and your SPA on localhost:64321 you can’t access the Rails app from the SPA with Ajax calls without some setup.




Read carefully, but note that Rails applications by default protect from XSS using protect_from_forgery with: :exception

There’s an excellent explanation about Rails CSRF protection scheme here: A Deep Dive into CSRF Protection in Rails

There are a lot of good articles about solving the CSRF for a SPA app using Rails as a backend. Basically you read the META tag with name “crsf-token” OR take it from the session cookie “csrf-token”.






Clean HTTP OPTIONS handling in Rails

Cross-Origin Resource Sharing for JSON and RAILS

Cross-Origin Resource Sharing for JSON and RAILS

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.