Warning
This module will be deprecated before EOY in favor of the built-in Nitro WebSocket.
Just another socket.io module for Nuxt 3.
This module uses the Vite server in development and req.socket.server
in production.
pnpm add nuxt3-socket.io
export default defineNuxtConfig({
modules: ['nuxt3-socket.io'],
socket: {
// JSON serializable options only.
// options object to pass when instantiating socket server.
serverOptions: {}
}
})
<script setup>
const { $io } = useNuxtApp()
const connected = ref(false)
onMounted(() => {
const socket = $io('http://localhost:3000')
socket.on('connect', () => {
connected.value = socket.connected
})
socket.on('disconnect', () => {
connected.value = socket.connected
})
})
</script>
<template>
<div>Connected: {{ connected }}</div>
</template>
By default, this module automatically creates a server instance. If you want access to that server instance, you can expose functions inside server/socket
and use the defineIOHandler
wrapper function:
// server/socket/example.ts
import { defineIOHandler } from 'nuxt3-socket.io/helpers'
export default defineIOHandler((io) => {
io.on('connection', (socket) => {
console.log('Connected ', socket.id)
})
})
It's recommended to roll your own socket server if you need more customization other than what is specified here.
- Run
npm run dev:prepare
to generate type stubs. - Use
npm run dev
to start playground in development mode.
MIT