Skip to content

Commit aec37c4

Browse files
committed
Add Supabase presence sync to user join/disconnect
Integrates Supabase Admin Client to update user presence in the 'user_presence' table when users join or disconnect. Falls back to local presence tracking if Supabase credentials are missing. Includes error handling and logs for presence updates.
1 parent b6dcd5b commit aec37c4

1 file changed

Lines changed: 50 additions & 4 deletions

File tree

server.js

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,52 @@ app.prepare().then(() => {
3232
},
3333
})
3434

35+
// Initialize Supabase Admin Client for server-side operations
36+
const { createClient } = require('@supabase/supabase-js')
37+
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
38+
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SERVICE_KEY
39+
40+
let supabase = null
41+
if (supabaseUrl && supabaseServiceKey) {
42+
supabase = createClient(supabaseUrl, supabaseServiceKey, {
43+
auth: {
44+
autoRefreshToken: false,
45+
persistSession: false
46+
}
47+
})
48+
console.log('✓ Supabase Admin Client initialized for Presence Sync')
49+
} else {
50+
console.warn('⚠ Missing Supabase Service Key - Presence Sync will be local only')
51+
}
52+
3553
// Store active users and their rooms
3654
const activeUsers = new Map()
3755

3856
io.on('connection', (socket) => {
3957
console.log('✓ Client connected:', socket.id)
4058

4159
// User joins with their info
42-
socket.on('user:join', (userData) => {
60+
socket.on('user:join', async (userData) => {
4361
activeUsers.set(socket.id, {
4462
...userData,
4563
rooms: new Set(),
4664
})
4765

66+
// Update DB Presence if Supabase is available
67+
if (supabase && userData.userId) {
68+
try {
69+
await supabase.from('user_presence').upsert({
70+
user_id: userData.userId,
71+
email: userData.email,
72+
name: userData.name,
73+
status: 'online',
74+
last_seen: new Date().toISOString()
75+
})
76+
} catch (err) {
77+
console.error('Error updating presence:', err)
78+
}
79+
}
80+
4881
// Broadcast user online status
4982
io.emit('user:status', {
5083
userId: userData.userId,
@@ -94,8 +127,6 @@ app.prepare().then(() => {
94127

95128
// Send message to room
96129
socket.on('message:send', (data) => {
97-
console.log(`📨 Message sent to room ${data.roomId}`)
98-
99130
// Broadcast to all clients in the room
100131
io.to(data.roomId).emit('message:new', {
101132
roomId: data.roomId,
@@ -128,7 +159,7 @@ app.prepare().then(() => {
128159
})
129160

130161
// Disconnect
131-
socket.on('disconnect', () => {
162+
socket.on('disconnect', async () => {
132163
const user = activeUsers.get(socket.id)
133164
if (user) {
134165
// Notify all rooms user was in
@@ -141,6 +172,21 @@ app.prepare().then(() => {
141172
})
142173
})
143174

175+
// Update DB Presence if Supabase is available
176+
if (supabase && user.userId) {
177+
try {
178+
await supabase.from('user_presence').upsert({
179+
user_id: user.userId,
180+
email: user.email,
181+
name: user.name,
182+
status: 'offline',
183+
last_seen: new Date().toISOString()
184+
})
185+
} catch (err) {
186+
console.error('Error updating presence override:', err)
187+
}
188+
}
189+
144190
// Broadcast user offline status
145191
io.emit('user:status', {
146192
userId: user.userId,

0 commit comments

Comments
 (0)