Send the Access Token from the Browser
The browser must provide an access token when establishing the Socket.IO connection.
For demonstration purposes, assume the application already has an access token issued by a trusted login system.
The token can be passed through the Socket.IO auth configuration.
Do not generate trusted user identities using values supplied through ordinary form fields.
JavaScript-readable localStorage tokens are vulnerable to theft through successful XSS attacks. Choose token storage and transport according to your application's threat model. HttpOnly cookies can reduce direct JavaScript access, but cookie-based Socket.IO authentication also requires careful origin and CSRF protection.
const accessToken = window.localStorage.getItem('accessToken');
const socket = io({
auth: {
token: accessToken
}
});
socket.on('connect', () => {
console.log('Authenticated socket connected');
});
socket.on('connect_error', (error) => {
console.error('Connection rejected:', error.message);
});Provides an existing access token to Socket.IO during connection establishment. The example assumes the application has already authenticated the user.
The Socket.IO auth option sends connection credentials.
The server remains responsible for verification.
Choose secure token storage appropriate to the application.