From ea8fdf448513722c663b978f084d83a6ba04085d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Wed, 22 Jan 2025 16:19:50 +0100 Subject: [PATCH] chore: ready --- README.md | 59 ++++++++++++++++++++++++++++ playground/app.vue | 7 ---- playground/nuxt.config.ts | 2 +- playground/package.json | 2 + playground/pages/index.vue | 8 ++++ playground/pages/sockets.vue | 26 ++++++++++++ playground/server/routes/ws.ts | 13 ++++++ playground/server/routes/ws/index.ts | 15 ------- pnpm-lock.yaml | 25 ++++++++++++ src/module.ts | 1 - src/runtime/server/plugins/ws.ts | 1 - src/runtime/server/utils/session.ts | 15 +++++-- 12 files changed, 145 insertions(+), 29 deletions(-) create mode 100644 playground/pages/sockets.vue create mode 100644 playground/server/routes/ws.ts delete mode 100644 playground/server/routes/ws/index.ts 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) - }) -})