DEV Community

Anya Brun
Anya Brun

Posted on • Updated on

Disable Request-Forgery Protection

NOTE: I wrote this blog post some time ago for Phase 4 of my Flatiron School SE program.

While setting up the api for my project, I came across an interesting bug. Naturally, for my JS front-end to be able to make fetch requests to the Rails back-end, I needed to enable cross-origin resource sharing. Now, I'd typically just go into the CORS config file and allow all origins with the wildcard:

# config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end
Enter fullscreen mode Exit fullscreen mode

Interestingly, I was still getting errors saying that fetch requests from my front-end were being blocked. After a great deal of googling and digging through Rails pull requests on github, I stumbled upon section 7.2 of the Action Cable Rails guide—wherein I discovered the following piece of code:

# config/environment/development.rb

config.action_cable.disable_request_forgery_protection = true
Enter fullscreen mode Exit fullscreen mode

This line of code disables and allows requests from any origin. An array of strings can also be passed in to specify from which origins requests may be accepted.

So enabling CORS requires not only adjusting the cors.rb file, but also going into development.rb and setting disable_request_forgery_protection equal to true.

Tangentially-related side note: some time ago, I came across an article talking about the need to keep a "developer journal." For now, my developer journal is just a document with a list of errors I come across and links to articles that helped me fix them. It helps prevent the same bugs from occurring again and provides a repo of information I can dig into later for deeper understanding of certain topics.

Once my backend was set up, I was able to start making AJAX requests. AJAX stands for Asynchronous Javascript And XML—although AJAX requests can be formatted as plain text or JSON.

When an event occurs (e.g., pressing a button), JS creates an XMLHttpRequest object that is sent to the web server (i.e., the Rails api). The server processes the request, and sends the response which is read and acted on by JavaScript.

JSON, by the way, is JavaScript Object Notation. Our Rails api "speaks" Ruby and the browser "speaks" JavaScript. Hence, the api converts Ruby objects into JSON (using serializers) before sending them to the frontend, so that the JS-speaking browser can then understand and use the data.

That's a pretty simplified understanding, but it was what I needed to enable back-and-forth communication between the client-side of my application and the server.

Top comments (0)