I am trying to use one of my queries inside of my websocket server but when I do, the context.user doesn't exist. Even if I make sure that I'm calling this query after the user is authenticated. I'm not sure why context.user isn't populated, but it got me to thinking if maybe I should only be using the queries from the client side? Surely there's a way to do it server side though?
and in my ws-server.ts I'm attempting to use it like this.
import { getListingSubscribers, getSubscriptionsByUser } from './queries'; // Import the getListingSubscribers function//Skipping a bunch of unrelated code... socket.on('userAuthenticated', async () => { console.log('User authenticated:', username); // Check if the user is authenticated before trying to rejoin rooms if (socket.data.user) { try { //TODO There is an error here. context.user doesn't exist and so we can't fetch subscriptions here. // It's all happening before the user is fully authenticated apparently. const subscriptions = await getSubscriptionsByUser(undefined, context); subscriptions.forEach(sub => { const room = `listing_${sub.listingId}`; socket.join(room); console.log(`${username} rejoined room ${room}`); }); } catch (error) { console.error('Error rejoining rooms:', error); } } else { console.warn('User not authenticated, skipping room rejoining.'); }});
import { getListingSubscribers, getSubscriptionsByUser } from './queries'; // Import the getListingSubscribers function//Skipping a bunch of unrelated code... socket.on('userAuthenticated', async () => { console.log('User authenticated:', username); // Check if the user is authenticated before trying to rejoin rooms if (socket.data.user) { try { //TODO There is an error here. context.user doesn't exist and so we can't fetch subscriptions here. // It's all happening before the user is fully authenticated apparently. const subscriptions = await getSubscriptionsByUser(undefined, context); subscriptions.forEach(sub => { const room = `listing_${sub.listingId}`; socket.join(room); console.log(`${username} rejoined room ${room}`); }); } catch (error) { console.error('Error rejoining rooms:', error); } } else { console.warn('User not authenticated, skipping room rejoining.'); }});
The end goal of all this is to emit a signal when the user is authenticated, so that I can make sure that context.user exists, and then I can add the user back into any websocket rooms they belong to as a way to persist that connection between server restarts during development.
I always get a 401 no matter what though, and context.user just doesn't exist. Any suggestions here? I'm not sure what I'm doing wrong.
Similar Threads
Continue the conversation
Join the Discord to ask follow-up questions and connect with the community
W
Wasp
Rails-like framework for React, Node.js and Prisma. Build your app in a day and deploy it with a single CLI command.