Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

n3pix's avatar
Level 1

How to authenticate API requests from Socket.io server?

I have a Next.js frontend application, you can say it's an SPA web app. I use Laravel for session management in my frontend app and I issue a Personal Access Token (PAT) for each authenticated session when a user is logged in or registered, until the session is closed when the user logs out. User uses this PAT to authenticate with Socket.io server and make requests from Socket.io.

But for some reason, my existing session changes ID without I'm knowing it and since this change isn't caused by logging in or registering I don't know when it happens. Due to that reason, I don't issue a PAT for that updated session and when user tries to connect to Socket.io server, they can not be authenticated even though they are logged in on the web app.

What do you suggest? Is there some bad aspects to my approach?

1 like
1 reply
vincent15000's avatar

Have a look at this page.

https://laravel.com/docs/12.x/broadcasting#client-pusher-channels

You can use pusher-js on client side to connect to socket.io.

const connectToWebsocket = () => {
    const websocket = new Pusher(ws_app_key, {
        wsHost: ws_url,
        wsPort: ws_port,
        forceTLS: false,
        encrypted: false,
        enableStats: false,
        enabledTransports: ['ws', 'wss'],
        cluster: ws_cluster,
        channelAuthorization: {
            endpoint: '/api/broadcasting/auth',
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('yggdraToken'),
            },
        },
        activityTimeout: 1000,
        pongTimeout: 1000,
        logLevel: 'OFF',
    });

You need to add these lines to authenticate.

channelAuthorization: {
    endpoint: '/api/broadcasting/auth',
    headers: {
        'Authorization': 'Bearer ' + sessionStorage.getItem('yggdraToken'),
    },
},

Please or to participate in this conversation.