Top Related Projects
Next-gen, Pusher-compatible, open-source WebSockets server. Simple, fast, and resilient. 📣
Websockets for Laravel. Done right.
Laravel Echo library for beautiful Pusher and Ably integration.
Pusher Javascript library
Supercharge your Laravel application's performance.
Dashboard and code-driven configuration for Laravel queues.
Quick Overview
Laravel Echo Server is a Node.js server for Laravel Echo broadcasting with Socket.io. It allows real-time event broadcasting in Laravel applications without the need for a separate WebSocket server like Pusher. This project enables developers to implement real-time features in their Laravel applications using a self-hosted solution.
Pros
- Self-hosted solution, providing more control over the broadcasting infrastructure
- Cost-effective alternative to third-party services like Pusher
- Seamless integration with Laravel Echo client
- Supports both public and private channels for flexible event broadcasting
Cons
- Requires additional server setup and maintenance compared to managed solutions
- May have scalability limitations for very large applications
- Less documentation and community support compared to more popular alternatives
- Not actively maintained (last commit was in 2021)
Code Examples
- Configuring Laravel Echo Server:
module.exports = {
authHost: 'http://localhost',
authEndpoint: '/broadcasting/auth',
clients: [],
database: 'redis',
databaseConfig: {
redis: {},
sqlite: {
databasePath: '/database/laravel-echo-server.sqlite'
}
},
devMode: true,
host: null,
port: 6001,
protocol: 'http',
socketio: {},
sslCertPath: '',
sslKeyPath: '',
sslCertChainPath: '',
sslPassphrase: '',
subscribers: {
http: true,
redis: true
},
apiOriginAllow: {
allowCors: false,
allowOrigin: '',
allowMethods: '',
allowHeaders: ''
}
};
- Broadcasting an event from Laravel:
event(new App\Events\NewMessage($message));
- Listening for events on the client-side:
Echo.channel('chat')
.listen('NewMessage', (e) => {
console.log('New message received:', e.message);
});
Getting Started
-
Install Laravel Echo Server:
npm install -g laravel-echo-server
-
Initialize the server in your Laravel project directory:
laravel-echo-server init
-
Start the server:
laravel-echo-server start
-
Configure Laravel to use the Echo Server driver in
config/broadcasting.php
:'default' => 'redis', 'connections' => [ 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], ],
-
Install Laravel Echo and Socket.io client in your frontend:
npm install --save laravel-echo socket.io-client
-
Configure Laravel Echo in your JavaScript:
import Echo from 'laravel-echo'; import io from 'socket.io-client'; window.io = io; window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });
Competitor Comparisons
Next-gen, Pusher-compatible, open-source WebSockets server. Simple, fast, and resilient. 📣
Pros of soketi
- Written in TypeScript, offering better type safety and developer experience
- Supports horizontal scaling out of the box, allowing for better performance in large-scale applications
- Provides a more extensive set of features, including presence channels and client events
Cons of soketi
- Requires more setup and configuration compared to laravel-echo-server
- May have a steeper learning curve for developers new to WebSocket servers
- Less tightly integrated with Laravel ecosystem
Code Comparison
soketi:
import { Soketi } from '@soketi/soketi';
const server = new Soketi({
appManager: new SimpleAppManager(),
adapter: new LocalAdapter(),
});
server.start();
laravel-echo-server:
const echo = require('laravel-echo-server');
echo.run({
authHost: 'http://localhost',
devMode: true,
database: 'redis',
databaseConfig: {
redis: {}
}
});
Both projects serve as WebSocket servers for real-time applications, but soketi offers more flexibility and scalability at the cost of increased complexity. laravel-echo-server is more straightforward to set up and use, especially within the Laravel ecosystem, but may lack some advanced features and scalability options provided by soketi.
Websockets for Laravel. Done right.
Pros of Laravel WebSockets
- Native PHP implementation, easier to integrate and deploy
- Supports horizontal scaling with Redis
- Includes a debug dashboard for real-time monitoring
Cons of Laravel WebSockets
- May have slightly higher resource usage
- Lacks some advanced features like presence channels
Code Comparison
Laravel WebSockets:
use BeyondCode\LaravelWebSockets\WebSocketsServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->register(WebSocketsServiceProvider::class);
}
}
Laravel Echo Server:
const echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
Laravel WebSockets is a PHP-based WebSocket server for Laravel, while Laravel Echo Server is a Node.js implementation. Laravel WebSockets integrates more seamlessly with Laravel applications and provides a debug dashboard, making it easier to monitor and troubleshoot WebSocket connections. However, it may consume more resources compared to Laravel Echo Server.
Laravel Echo Server, being Node.js-based, might offer better performance for high-traffic applications but requires additional setup and maintenance of a separate Node.js environment. It also supports presence channels out of the box, which Laravel WebSockets lacks.
Both solutions work well with Laravel Echo on the client-side, allowing for easy integration of real-time features in Laravel applications. The choice between them often depends on specific project requirements and the development team's expertise.
Laravel Echo library for beautiful Pusher and Ably integration.
Pros of Laravel Echo
- Written in TypeScript, offering better type safety and developer experience
- Seamless integration with Laravel's broadcasting system
- More actively maintained with frequent updates and bug fixes
Cons of Laravel Echo
- Requires a separate WebSocket server (e.g., Pusher or Socket.io)
- May have a steeper learning curve for developers new to Laravel's ecosystem
Code Comparison
Laravel Echo:
import Echo from 'laravel-echo';
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-key'
});
Laravel Echo Server:
var echo = require('laravel-echo-server');
echo.run({
authHost: 'http://localhost',
devMode: true
});
Key Differences
- Laravel Echo is a client-side library, while Laravel Echo Server is a standalone server
- Echo Server provides an all-in-one solution, including WebSocket functionality
- Echo requires additional setup for WebSocket connections but offers more flexibility
Use Cases
- Laravel Echo: Ideal for projects already using Laravel's broadcasting system or requiring client-side real-time updates
- Echo Server: Better suited for projects needing a simple, self-hosted WebSocket server without external dependencies
Community and Support
- Laravel Echo has a larger community and more extensive documentation
- Echo Server has a dedicated user base but less frequent updates
Pusher Javascript library
Pros of pusher-js
- Easier to set up and use, with extensive documentation and examples
- Supports multiple platforms and frameworks beyond Laravel
- Offers additional features like presence channels and client events
Cons of pusher-js
- Requires a paid subscription for production use beyond free tier limits
- Relies on external servers, potentially introducing latency and privacy concerns
- Less customizable compared to self-hosted solutions
Code Comparison
laravel-echo-server:
const echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
echo.channel('orders')
.listen('OrderShipped', (e) => {
console.log(e.order.name);
});
pusher-js:
const pusher = new Pusher('YOUR_APP_KEY', {
cluster: 'YOUR_APP_CLUSTER'
});
const channel = pusher.subscribe('orders');
channel.bind('OrderShipped', function(data) {
console.log(data.order.name);
});
Both libraries provide similar functionality for real-time communication, but pusher-js offers a more straightforward setup process and broader platform support. However, laravel-echo-server provides greater control and customization options as a self-hosted solution, potentially reducing costs for high-volume applications.
Supercharge your Laravel application's performance.
Pros of Laravel Octane
- Significantly improves application performance by keeping the application in memory
- Supports multiple high-performance application servers like Swoole and RoadRunner
- Provides automatic reloading of workers for seamless deployment
Cons of Laravel Octane
- Requires additional server configuration and setup
- May not be compatible with all Laravel packages and extensions
- Potential memory leaks if not managed properly
Code Comparison
Laravel Octane:
use Laravel\Octane\Facades\Octane;
Octane::route('GET', '/api/users', function () {
return User::all();
});
Laravel Echo Server:
const echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
echo.channel('orders')
.listen('OrderShipped', (e) => {
console.log(e.order.name);
});
Key Differences
Laravel Octane focuses on improving overall application performance by leveraging persistent application instances, while Laravel Echo Server is specifically designed for real-time event broadcasting. Octane is integrated directly into the Laravel application, whereas Echo Server runs as a separate Node.js process. Octane's primary goal is to enhance request handling speed, while Echo Server facilitates real-time communication between the server and clients.
Dashboard and code-driven configuration for Laravel queues.
Pros of Horizon
- Built-in dashboard for monitoring and managing Laravel queues
- Seamless integration with Laravel's ecosystem and configuration
- Supports multiple queue drivers (Redis, Amazon SQS, etc.)
Cons of Horizon
- Limited to Laravel applications, unlike Echo Server's broader compatibility
- Requires Redis as the queue driver for optimal performance
- More complex setup compared to Echo Server's simplicity
Code Comparison
Horizon configuration:
'horizon' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'simple',
'processes' => 10,
'tries' => 3,
],
],
Echo Server configuration:
{
"authHost": "http://localhost",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {}
}
}
Key Differences
- Horizon focuses on queue management, while Echo Server handles real-time broadcasting
- Horizon provides a more comprehensive solution for Laravel queue monitoring and management
- Echo Server is more flexible for use with non-Laravel projects
- Horizon requires deeper integration with Laravel, whereas Echo Server can be set up as a standalone service
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Laravel Echo Server
NodeJs server for Laravel Echo broadcasting with Socket.io.
System Requirements
The following are required to function properly.
- Laravel 5.3
- Node 6.0+
- Redis 3+
Additional information on broadcasting with Laravel can be found on the official docs: https://laravel.com/docs/master/broadcasting
Getting Started
Install npm package globally with the following command:
$ npm install -g laravel-echo-server
Initialize with CLI Tool
Run the init command in your project directory:
$ laravel-echo-server init
The cli tool will help you setup a laravel-echo-server.json file in the root directory of your project. This file will be loaded by the server during start up. You may edit this file later on to manage the configuration of your server.
API Clients
The Laravel Echo Server exposes a light http API to perform broadcasting functionality. For security purposes, access to these endpoints from http referrers must be authenticated with an APP id and key. This can be generated using the cli command:
$ laravel-echo-server client:add APP_ID
If you run client:add
without an app id argument, one will be generated for you. After running this command, the client id and key will be displayed and stored in the laravel-echo-server.json file.
In this example, requests will be allowed as long as the app id and key are both provided with http requests.
Request Headers
Authorization: Bearer skti68i...
or
http://app.dev:6001/apps/APP_ID/channels?auth_key=skti68i...
You can remove clients with laravel-echo-server client:remove APP_ID
Run The Server
in your project root directory, run
$ laravel-echo-server start
Stop The Server
in your project root directory, run
$ laravel-echo-server stop
Configurable Options
Edit the default configuration of the server by adding options to your laravel-echo-server.json file.
Title | Default | Description |
---|---|---|
apiOriginAllow | {} | Configuration to allow API be accessed over CORS. Example |
authEndpoint | /broadcasting/auth | The route that authenticates private channels |
authHost | http://localhost | The host of the server that authenticates private and presence channels |
database | redis | Database used to store data that should persist, like presence channel members. Options are currently redis and sqlite |
databaseConfig | {} | Configurations for the different database drivers Example |
devMode | false | Adds additional logging for development purposes |
host | null | The host of the socket.io server ex.app.dev . null will accept connections on any IP-address |
port | 6001 | The port that the socket.io server should run on |
protocol | http | Must be either http or https |
sslCertPath | '' | The path to your server's ssl certificate |
sslKeyPath | '' | The path to your server's ssl key |
sslCertChainPath | '' | The path to your server's ssl certificate chain |
sslPassphrase | '' | The pass phrase to use for the certificate (if applicable) |
socketio | {} | Options to pass to the socket.io instance (available options) |
subscribers | {"http": true, "redis": true} | Allows to disable subscribers individually. Available subscribers: http and redis |
DotEnv
If a .env file is found in the same directory as the laravel-echo-server.json file, the following options can be overridden:
authHost
:LARAVEL_ECHO_SERVER_AUTH_HOST
Note: This option will fall back to theLARAVEL_ECHO_SERVER_HOST
option as the default if that is set in the .env file.host
:LARAVEL_ECHO_SERVER_HOST
port
:LARAVEL_ECHO_SERVER_PORT
devMode
:LARAVEL_ECHO_SERVER_DEBUG
databaseConfig.redis.host
:LARAVEL_ECHO_SERVER_REDIS_HOST
databaseConfig.redis.port
:LARAVEL_ECHO_SERVER_REDIS_PORT
databaseConfig.redis.password
:LARAVEL_ECHO_SERVER_REDIS_PASSWORD
protocol
:LARAVEL_ECHO_SERVER_PROTO
sslKeyPath
:LARAVEL_ECHO_SERVER_SSL_KEY
sslCertPath
:LARAVEL_ECHO_SERVER_SSL_CERT
sslPassphrase
:LARAVEL_ECHO_SERVER_SSL_PASS
sslCertChainPath
:LARAVEL_ECHO_SERVER_SSL_CHAIN
Running with SSL
- Your client side implementation must access the socket.io client from https.
- The server configuration must set the server host to use https.
- The server configuration should include paths to both your ssl certificate and key located on your server.
Note: This library currently only supports serving from either http or https, not both.
Alternative SSL implementation
If you are struggling to get SSL implemented with this package, you could look at using a proxy module within Apache or NginX. Essentially, instead of connecting your websocket traffic to https://yourserver.dev:6001/socket.io?..... and trying to secure it, you can connect your websocket traffic to https://yourserver.dev/socket.io. Behind the scenes, the proxy module of Apache or NginX will be configured to intercept requests for /socket.io, and internally redirect those to your echo server over non-ssl on port 6001. This keeps all of the traffic encrypted between browser and web server, as your web server will still do the SSL encryption/decryption. The only thing that is left unsecured is the traffic between your webserver and your Echo server, which might be acceptable in many cases.
Sample NginX proxy config
#the following would go within the server{} block of your web server config
location /socket.io {
proxy_pass http://laravel-echo-server:6001; #could be localhost if Echo and NginX are on the same box
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
Sample Apache proxy config
RewriteCond %{REQUEST_URI} ^/socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://localhost:6001/$1 [P,L]
ProxyPass /socket.io http://localhost:6001/socket.io
ProxyPassReverse /socket.io http://localhost:6001/socket.io
Setting the working directory
The working directory in which laravel-echo-server
will look for the configuration file laravel-echo-server.json
can be passed to the start
command through the --dir
parameter like so: laravel-echo-server start --dir=/var/www/html/example.com/configuration
Subscribers
The Laravel Echo Server subscribes to incoming events with two methods: Redis & Http.
Redis
Your core application can use Redis to publish events to channels. The Laravel Echo Server will subscribe to those channels and broadcast those messages via socket.io.
Http
Using Http, you can also publish events to the Laravel Echo Server in the same fashion you would with Redis by submitting a channel
and message
to the broadcast endpoint. You need to generate an API key as described in the API Clients section and provide the correct API key.
Request Endpoint
POST http://app.dev:6001/apps/your-app-id/events?auth_key=skti68i...
Request Body
{
"channel": "channel-name",
"name": "event-name",
"data": {
"key": "value"
},
"socket_id": "h3nAdb134tbvqwrg"
}
channel - The name of the channel to broadcast an event to. For private or presence channels prepend private-
or presence-
.
channels - Instead of a single channel, you can broadcast to an array of channels with 1 request.
name - A string that represents the event key within your app.
data - Data you would like to broadcast to channel.
socket_id (optional) - The socket id of the user that initiated the event. When present, the server will only "broadcast to others".
Pusher
The HTTP subscriber is compatible with the Laravel Pusher subscriber. Just configure the host and port for your Socket.IO server and set the app id and key in config/broadcasting.php. Secret is not required.
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => null,
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'host' => 'localhost',
'port' => 6001,
'scheme' => 'http'
],
],
You can now send events using HTTP, without using Redis. This also allows you to use the Pusher API to list channels/users as described in the Pusher PHP library
HTTP API
The HTTP API exposes endpoints that allow you to gather information about your running server and channels.
Status Get total number of clients, uptime of the server, and memory usage.
GET /apps/:APP_ID/status
Channels List of all channels.
GET /apps/:APP_ID/channels
Channel Get information about a particular channel.
GET /apps/:APP_ID/channels/:CHANNEL_NAME
Channel Users List of users on a channel.
GET /apps/:APP_ID/channels/:CHANNEL_NAME/users
Cross Domain Access To API
Cross domain access can be specified in the laravel-echo-server.json file by changing allowCors
in apiOriginAllow
to true
. You can then set the CORS Access-Control-Allow-Origin, Access-Control-Allow-Methods as a comma separated string (GET and POST are enabled by default) and the Access-Control-Allow-Headers that the API can receive.
Example below:
{
"apiOriginAllow":{
"allowCors" : true,
"allowOrigin" : "http://127.0.0.1",
"allowMethods" : "GET, POST",
"allowHeaders" : "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}
}
This allows you to send requests to the API via AJAX from an app that may be running on the same domain but a different port or an entirely different domain.
Database
To persist presence channel data, there is support for use of Redis or SQLite as a key/value store. The key being the channel name, and the value being the list of presence channel members.
Each database driver may be configured in the laravel-echo-server.json file under the databaseConfig
property. The options get passed through to the database provider, so developers are free to set these up as they wish.
Redis
For example, if you wanted to pass a custom configuration to Redis:
{
"databaseConfig" : {
"redis" : {
"port": "3001",
"host": "redis.app.dev",
"keyPrefix": "my-redis-prefix"
}
}
}
Note: No scheme (http/https etc) should be used for the host address
A full list of Redis options can be found here.
Redis sentinel
For example, if you wanted to use redis-sentinel, you need to pass a custom configuration :
"databaseConfig": {
"redis": {
"sentinels": [
{
"host": "redis-sentinel-0",
"port": 26379
},
{
"host": "redis-sentinel-1",
"port": 26379
}
{
"host": "redis-sentinel-2",
"port": 26379
}
],
"name": "mymaster",
"sentinelPassword": "redis-password"
},
},
For more information about redis sentinel configuration you can check this
SQLite
With SQLite you may be interested in changing the path where the database is stored.
{
"databaseConfig" : {
"sqlite" : {
"databasePath": "/path/to/laravel-echo-server.sqlite"
}
}
}
Note 1: The path is relative to the root of your application, not your system.
Note 2: node-sqlite3 is required for this database. Please install before using.
npm install sqlite3 -g
Presence Channels
When users join a presence channel, their presence channel authentication data is stored using Redis.
While presence channels contain a list of users, there will be instances where a user joins a presence channel multiple times. For example, this would occur when opening multiple browser tabs. In this situation "joining" and "leaving" events are only emitted to the first and last instance of the user.
Optionally, you can configure laravel-echo-server to publish an event on each update to a presence channel, by setting databaseConfig.publishPresence
to true
:
{
"database": "redis",
"databaseConfig": {
"redis" : {
"port": "6379",
"host": "localhost"
},
"publishPresence": true
}
}
You can use Laravel's Redis integration, to trigger Application code from there:
Redis::subscribe(['PresenceChannelUpdated'], function ($message) {
var_dump($message);
});
Client Side Configuration
See the official Laravel documentation for more information. https://laravel.com/docs/master/broadcasting#introduction
Tips
Socket.io client library
You can include the socket.io client library from your running server. For example, if your server is running at app.dev:6001
you should be able to
add a script tag to your html like so:
<script src="//app.dev:6001/socket.io/socket.io.js"></script>
Note: When using the socket.io client library from your running server, remember to check that the io
global variable is defined before subscribing to events.
µWebSockets deprecation
µWebSockets has been officially deprecated. Currently there is no support for µWebSockets in Socket.IO, but it may have the new ClusterWS support incoming. Meanwhile Laravel Echo Server will use ws
engine by default until there is another option.
Top Related Projects
Next-gen, Pusher-compatible, open-source WebSockets server. Simple, fast, and resilient. 📣
Websockets for Laravel. Done right.
Laravel Echo library for beautiful Pusher and Ably integration.
Pusher Javascript library
Supercharge your Laravel application's performance.
Dashboard and code-driven configuration for Laravel queues.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot