title: Rails 4: Set a cookie in a request/response if type is JSON?
body: <p>How do I set a cookie when responding to a request of type application/json in Rails?  </p>
  
  <p>The controller action works as expected but there is no cookie being set and there is no Set-Cookie header in the response.  Any help will be greatly appreciated.</p>
  
  <p>Controller:</p>
  
  <pre><code>class SessionsController &lt; ApplicationController
  
      def create
          @user = User.find_by(email: params[:session][:email].downcase)
          if user &amp;&amp; user.authenticate(params[:session][:password])
              log_in(user)
              .
              .
              cookies[:test] = 'Test cookie'
  
              render json: @user
              #render json: @user, set_cookie: 'test' #Also tried this
          else
              render text: 'Wrong username and/or password', status: 401
          end
      end
  
  end
  </code></pre>
  
  <p>Route:</p>
  
  <pre><code>Rails.application.routes.draw do
  
      .
      .
      resources :sessions, :defaults =&gt; { :format =&gt; :json }
  
  end
  </code></pre>