How to stop Rails from setting a session cookie

Recently I was working on a Rails API and I wanted to stop Rails from setting it's _session cookie for API requests.

Since these requests are authenticated via an API token, there's no reason for the cookie to be returned to the user.

# application_controller.rb
after_action lambda {
  request.session_options[:skip] = current_api_token.present?
}

def current_api_token
  # Only returns a value if auth is via an API token
end

Writing a test

If you'd like to test it. Here's a quick example using minitest.

test "when authed with a service token, cookies are not set" do
  get some_path, headers: # your token auth here

  assert_response :success
  assert_empty response.cookies
end

test "when authed as user, cookies are set" do
  user = create(:user)
  sign_in user

  get some_path

  assert_response :success
  assert response.cookies
end