skip to Main Content

I’m working a Laravel and React Native project where real-time communication is crucial. In scenario where a user updates their profile other users should get the update in real time. And a chatting functionality to be integrated as well.

Currently, I’m using Laravel & Reverb on the backend. I installed socket.io-client on the RN Expo app but the connection is never established.

Don’t know why that is though. I need help on how to integrate this correctly.

2

Answers


  1. I ran into this exact same issue a few months ago. The problem is that you’re trying to use socket.io-client with Laravel Reverb, which won’t work out of the box since they use different protocols.

    Here’s how I got it working:

    Instead of socket.io-client, you’ll want to use laravel-echo with pusher-js. First, install these packages:

    npm install laravel-echo pusher-js
    

    Then set up your Echo configuration in your RN app like this:

    import Echo from 'laravel-echo';
    import Pusher from 'pusher-js/react-native';
    
    const echo = new Echo({
        broadcaster: 'pusher',
        client: new Pusher('your-key', {
            wsHost: 'your-host',
            wsPort: 8080,
            forceTLS: false,
            enabledTransports: ['ws', 'wss'],
            disableStats: true,
        }),
    });
    

    For the profile updates, create an event in Laravel:

    class ProfileUpdated implements ShouldBroadcast
    {
        public $user;
    
        public function __construct($user)
        {
            $this->user = $user;
        }
    
        public function broadcastOn()
        {
            return new Channel('profiles');
        }
    }
    

    Then listen for it in your React Native component:

    useEffect(() => {
        echo.channel('profiles')
            .listen('ProfileUpdated', (e) => {
                console.log('Profile updated:', e);
                // Update your UI here
            });
    
        return () => {
            echo.leave('profiles');
        };
    }, []);
    

    For the chat functionality, it’s pretty similar. Just make sure you’re using private channels if the chat needs to be secure:

    // Laravel Event
    class MessageSent implements ShouldBroadcast
    {
        public $message;
    
        public function broadcastOn()
        {
            return new PrivateChannel('chat.' . $this->message->room_id);
        }
    }
    
    // React Native
    echo.private(`chat.${roomId}`)
        .listen('MessageSent', (e) => {
            // Handle new message
        });
    

    Quick debugging tips:

    • Make sure Reverb is running (php artisan reverb:start)
    • Check your WebSocket URLs match
    • Verify your broadcasting config in Laravel
    • Look at the Network tab in dev tools to see if the WebSocket connection is being established
    Login or Signup to reply.
  2. First, let’s do a complete setup check:

    1. Laravel Backend Setup
    // config/broadcasting.php
    'reverb' => [
        'driver' => 'reverb',
        'host' => env('REVERB_HOST', 'localhost'),
        'port' => env('REVERB_PORT', 8080),
        'scheme' => env('REVERB_SCHEME', 'http'),
        'app_id' => env('REVERB_APP_ID'),
        'key' => env('REVERB_APP_KEY'),
    ],
    
    // .env
    BROADCAST_DRIVER=reverb
    REVERB_APP_ID=your_app_id
    REVERB_APP_KEY=your_app_key
    
    1. React Native Setup
    // echo-config.js
    import Echo from 'laravel-echo';
    import Pusher from 'pusher-js/react-native';
    
    const echo = new Echo({
        broadcaster: 'pusher',
        key: process.env.REVERB_APP_KEY,
        wsHost: process.env.REVERB_HOST,
        wsPort: 8080,
        forceTLS: false,
        encrypted: false,
        enabledTransports: ['ws', 'wss'],
        disableStats: true,
    });
    
    export default echo;
    
    1. Connection Test Component
    import React, { useEffect } from 'react';
    import echo from './echo-config';
    
    const ConnectionTest = () => {
        useEffect(() => {
            // Debug connection
            echo.connector.pusher.connection.bind('connecting', () => {
                console.log('Connecting...');
            });
            
            echo.connector.pusher.connection.bind('connected', () => {
                console.log('Connected!');
            });
            
            echo.connector.pusher.connection.bind('error', (err) => {
                console.error('Connection error:', err);
            });
    
            return () => {
                echo.disconnect();
            };
        }, []);
    
        return null;
    };
    

    Common issues and solutions:

    1. CORS Issues
    // config/cors.php
    return [
        'paths' => ['*'],
        'allowed_methods' => ['*'],
        'allowed_origins' => ['*'], // In production, specify your actual domain
        'allowed_origins_patterns' => [],
        'allowed_headers' => ['*'],
        'exposed_headers' => [],
        'max_age' => 0,
        'supports_credentials' => true,
    ];
    
    1. Network Configuration
    • Ensure your Laravel backend is accessible from your React Native app
    • Check if the WebSocket port (8080) is open and accessible
    • Verify your IP addresses/domains match exactly
    1. Debug Commands
    # Check if Reverb is running
    php artisan reverb:start
    
    # Test event broadcasting
    php artisan event:generate
    

    Share any error message after trying this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search