Skip to content

Instantly share code, notes, and snippets.

@retendo
Created May 31, 2020 12:14
Show Gist options
  • Save retendo/3e2ddb90a29dfd0f5a2ab81729c7ed29 to your computer and use it in GitHub Desktop.
Save retendo/3e2ddb90a29dfd0f5a2ab81729c7ed29 to your computer and use it in GitHub Desktop.
Supabase node.js proxy server
const { Socket } = require('@supabase/realtime-js');
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
wss.on('connection', function connection(ws) {
ws.send('Connection established.');
});
const socket = new Socket(process.env.REALTIME_URL || 'http://localhost:4000/socket')
socket.connect()
socket.channel('realtime:public')
.join()
.channel
.on('*', payload => {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
"type": payload.table,
"operation": payload.type,
"object": payload.record != null ? payload.record : payload.old_record
}));
}
});
})
{
"name": "realtime-proxy",
"scripts": {
"dev": "node index.js"
},
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@supabase/realtime-js": "^0.9.0",
"bufferutil": "^4.0.1",
"express": "^4.17.1",
"utf-8-validate": "^5.0.2",
"ws": "^7.3.0"
}
}
#!/bin/bash
docker rm -f realtime || true
docker run -d -p 4000:4000 --name=realtime \
-e DB_HOST='docker.for.mac.host.internal' \
-e DB_NAME="$POSTGRES_DB" \
-e DB_USER='postgres' \
-e DB_PASSWORD='' \
-e DB_PORT="$POSTGRES_PORT" \
-e PORT=4000 \
-e HOSTNAME='localhost' \
-e SECRET_KEY_BASE='SOMETHING_SUPER_SECRET' \
supabase/realtime
@retendo
Copy link
Author

retendo commented May 31, 2020

Run instructions:
Disclaimer: this works for me on Mac

  1. Have Docker and node/npm/yarn installed
  2. Save files to folder of your choice
  3. yarn install
  4. Refer to https://github.com/supabase/realtime#database-set-up for preparing database (maybe restart db server afterwards)
  5. Set POSTGRES_DB and POSTGRES_PORT env vars somehow or replace with hardcoded values in restart-realtime.sh
  6. ./restart-realtime.sh
  7. yarn run dev

To test:

  • Use some websocket test client, i.e. WebSocket Test Client Chrome extension or WebSocket Client from Mac AppStore
  • Connect to ws://localhost:3000
  • Change something in the database, i.e. use pgAdmin or plain psql
  • See adjusted JSON that got send in test client

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment