title: Single Page Application and CSRF Token
body: <p>I need to use a Single Page Application (React, Ember, Angular, I don't care) with Rails CSRF protection mechanism.</p>
  
  <p>I'm wondering if I need to create a token evey time in the <code>ApplicationController</code> like this:</p>
  
  <pre><code>class ApplicationController &lt; ActionController::Base
  
    after_action :set_csrf_cookie
  
    def set_csrf_cookie
      cookies["X-CSRF-Token"] = form_authenticity_token
    end
  
  end
  </code></pre>
  
  <p><strong>or I can just create a token once</strong>.</p>
  
  <p>Per session or per (non-GET) request?</p>
  
  <p>I think the token is still valid until the session is valid, right?</p>
  
  <p><strong>CLARIFY</strong>:</p>
  
  <p>I see Rails default application (server-rendered pages) update csrf-token each time I navigate a page. So every time it changes.</p>
  
  <p>So in my situation if I create a new token for each <code>after_action</code> the previous CSRF-Token is still good for that session. So, how to invalidate the previous token? I have to?</p>
  
  <p>Because only if I invalidate it makes sense, right?</p>