Action Cable
raw JSON →Action Cable is the WebSocket framework integrated into Ruby on Rails, providing real-time communication capabilities for Rails applications. The npm package 'actioncable' (current stable version 5.2.8-1, though the Rails ecosystem recommends using the latest 7.x or 8.x series) is the JavaScript client library that connects to an Action Cable server. It allows developers to subscribe to channels and receive broadcasts in the browser or any JavaScript runtime. Key differentiators: tight integration with Rails (session/cookie-based authentication, same MVC patterns), full-stack offering with both server- and client-side components, and pub-sub streaming model. Release cadence follows Rails releases, with frequent minor and patch updates. Alternatives include pure WebSocket libraries or Pusher, but Action Cable is the default for Rails real-time features.
Common errors
error WebSocket is not defined ↓
error Module not found: Can't resolve '@rails/actioncable' ↓
error TypeError: ActionCable.createConsumer is not a function ↓
error Cannot find module 'actioncable' or its corresponding type declarations. ↓
Warnings
breaking ActionCable.createConsumer() no longer accepts a function as argument; must pass a URL string or omit for default. ↓
deprecated The package @rails/actioncable (npm) is deprecated in favor of the actioncable package (npm). ↓
gotcha Importing 'actioncable' in Node.js without a WebSocket polyfill will throw: 'WebSocket is not defined'. ↓
gotcha TypeScript definitions are not included; you must install @types/actioncable separately. ↓
breaking ActionCable.Connection and ActionCable.Subscription are no longer publicly accessible; use createConsumer and subscriptions.create. ↓
Install
npm install actioncable yarn add actioncable pnpm add actioncable Imports
- ActionCable wrong
const ActionCable = require('actioncable')correctimport ActionCable from 'actioncable' - createConsumer wrong
import { createConsumer } from '@rails/actioncable'correctimport { createConsumer } from 'actioncable' - Consumer wrong
import { Consumer } from 'actioncable'correctimport type { Consumer } from 'actioncable' - createWebSocketURL wrong
import { createWebSocketURL } from 'actioncable/lib'correctimport { createWebSocketURL } from 'actioncable'
Quickstart
import ActionCable from 'actioncable';
const cable = ActionCable.createConsumer('ws://localhost:3000/cable');
const subscription = cable.subscriptions.create('ChatChannel', {
connected() {
console.log('Connected to ChatChannel');
},
disconnected() {
console.log('Disconnected');
},
received(data) {
console.log('Received:', data);
}
});
// Send data to server (requires server-side handling)
subscription.send({ message: 'Hello!' });
// Unsubscribe when done
subscription.unsubscribe();
cable.disconnect();