diff --git a/README.md b/README.md index 8adc659b..978f7ab9 100644 --- a/README.md +++ b/README.md @@ -596,6 +596,65 @@ You can use the `placeholder` slot to show a placeholder on server-side and whil If you are caching your routes with `routeRules`, please make sure to use [Nitro](https://github.com/unjs/nitro) >= `2.9.7` to support the client-side fetching of the user session. +## WebSockets + +Nuxt Auth Utils is compatible with [Nitro WebSockets](https://nitro.build/guide/websocket). + +Make sure to enable the `experimental.websocket` option in your `nuxt.config.ts`: + +```ts +export default defineNuxtConfig({ + nitro: { + experimental: { + websocket: true + } + } +}) +``` + +You can use the `requireUserSession` function in the `upgrade` function to check if the user is authenticated before upgrading the WebSocket connection. + +```ts +// server/routes/ws.ts +export default defineWebSocketHandler({ + async upgrade(request) { + // Make sure the user is authenticated before upgrading the WebSocket connection + await requireUserSession(request) + }, + async open(peer) { + const { user } = await requireUserSession(peer) + const username = Object.values(user).filter(Boolean).join(' ') + peer.send(`Hello, ${username}!`) + }, + message(peer, message) { + peer.send(`Echo: ${message}`) + }, +}) +``` + +Then, in your application, you can use the [useWebSocket](https://vueuse.org/core/useWebSocket/) composable to connect to the WebSocket: + +```vue + + + +``` + ## Configuration We leverage `runtimeConfig.session` to give the defaults option to [h3 `useSession`](https://h3.unjs.io/examples/handle-session). diff --git a/playground/app.vue b/playground/app.vue index e8cb4393..c04effbd 100644 --- a/playground/app.vue +++ b/playground/app.vue @@ -201,13 +201,6 @@ const providers = computed(() => external: true, })), ) - -onMounted(() => { - const ws = new WebSocket('/ws') - ws.addEventListener('message', (event) => { - console.log('message', event.data) - }) -})