WebSockets
Nuxflare Pro comes with a simple WebSockets pub/sub implementation based on Cloudflare Durable Objects.
The WebSocket implementation uses Cloudflare Workers and Durable Objects to provide real-time capabilities.
Architecture
- Frontend WebSocket client in
packages/app/app/plugins/websockets.ts
- Backend WebSocket server in
packages/functions/src/websockets.js
- Infrastructure setup in
infra/websockets.ts
Usage
Frontend
The WebSocket client is available as a Nuxt plugin. Access it in your components:
// In your component
const { $ws } = useNuxtApp();
// Subscribe to topics
$ws.on("user.123", (data) => {
// Handle topic payload
console.log("Got update:", data);
});
// Cleanup when done
onUnmounted(() => {
$ws.off("user.123");
});
The client automatically:
- Handles authentication using access tokens
- Reconnects on connection drops
- Resubscribes to topics after reconnection
Backend
Publish messages to topics:
async ({ ctx: { user, sendWebsocketsEvent }, input }) => {
// ...create notification in database...
await sendWebsocketsEvent(
user.id, // topic id
{
// topic payload
type: "notification",
payload: notification
}
);
});
Security
- Authentication uses OpenAuth.js JWT tokens passed via WebSocket protocol headers
- Topic authorization is easily customizable. Control access to specific topics based on user roles, permissions, or other criteria.
Configuration
Enable WebSockets by setting the websockets
flag in your configuration:
config.ts
export const flags = {
// ...
websockets: true,
};
This will:
- Deploy the WebSocket Worker
- Set up Durable Objects
- Configure the frontend client