You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Is this setup ok for react native? I seem to get xhr poll error sometimes. 'websocket' tranasport it's not working. Coupled with a nodejs http instance.
#4862
I am trying to properly set up a socket.io service in my React Native app, coupled with the socket configuration done on NodeJS.
As a note - we are using JWT authentication to authenticate the socket.io instance/connection request.
I am sometimes getting XHR poll error, especially I think when the JWT expires and tries to re-set it?
Can you help me please in looking if what I have created, is ok? Sharing here both the React Native ts file and also the NodeJS configuration. I am expecting this to not "fail" if not needed.
Thank you a lot!
A part of the NodeJS Config:
const ioConfig = {
cors: {
credentials: true,
origin: (origin, callback) => {
if (!origin || [
// ...list of origins...
].includes(origin)) { // no origin means it's a mobile client or from another non-browser source
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST'],
allowedHeaders: ['Authorization', 'useragent', 'fromNative'],
},
};
io = require('socket.io')(httpServer, ioConfig);
const httpServer = app.listen(port, () => console.log(`Listening on port ${port}..`));
const wrap = (middleware) => (socket, next) => middleware(socket.request, {}, next);
io.use(wrap(sessionMiddleware));
io.use(async (socket, next) => {
const { query, headers } = socket.handshake;
const bearerHeader = headers.authorization;
let token;
if (bearerHeader && bearerHeader.startsWith('Bearer ')) {
token = bearerHeader.split(' ')[1]; // This will extract the token after 'Bearer'
} else {
token = query.token; // If not found in the headers, attempt to get from query params
}
if (!token) return next(new Error('unauthorized'));
let user = false;
try {
user = await identityClient.validateToken(token, undefined, 'JWT');
} catch (error) {
console.error('Authentication error:', error);
}
if (!user) {
return next(new Error('unauthorized'));
}
// Attach user information to socket for further use
socket.user = { ...user, id: user.sub || user.userId };
next();
});
io.on('connection', (socket) => {
try {
const user = socket.request?.session?.user || socket.user;
let userId;
// Retrieve userId from session if available
if (user) {
userId = user.id; // Adjust according to the structure of your user object
}
// If userId is not available in session, retrieve it from query
if (!userId) {
userId = socket.handshake.query.userId;
}
if (userId && userId !== 'undefined') {
socket.join(userId);
io.to(userId).emit(`connected_${userId}`, true);
}
socket.on('disconnect', () => {
console.log('A user disconnected');
});
} catch (error) {
console.error('Error handling connection:', error);
captureException(error);
socket.emit('server_error', 'An error occurred on the server'); // Notify the client about the error
}
});
io.on('connect_error', (err) => {
console.log('Connection error:', err.message);
captureException(err);
});
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hello!
I am trying to properly set up a socket.io service in my React Native app, coupled with the socket configuration done on NodeJS.
As a note - we are using JWT authentication to authenticate the socket.io instance/connection request.
I am sometimes getting
XHR poll error
, especially I think when the JWT expires and tries to re-set it?Can you help me please in looking if what I have created, is ok? Sharing here both the React Native ts file and also the NodeJS configuration. I am expecting this to not "fail" if not needed.
Thank you a lot!
A part of the NodeJS Config:
A part of the React Native side:
Beta Was this translation helpful? Give feedback.
All reactions