Skip to content

xarenas107/nuxt-socket.io

Repository files navigation

Nuxt Socket.io

npm version npm downloads License Nuxt

A Nuxt module for socket.io

🚀 Features

  • Nuxt 3 ready
  • 👌 Zero config: Configuration for common use cases
  • Nitro ready: Integration with nitro server.
  • 🍍 Pinia ready: Integration with @pinia/nuxt module.
  • ⚙️ Auto import: Provide auto import functions for client and server side.
  • 🪝 Customizable: Provide hooks for customization on client and server side.
  • 🦾 Type strong: Written in typescript

📦 Install

npm i @xarenas107/nuxt-socket-io -D 

🦄 Usage

Add @xarenas107/nuxt-socket-io to the modules section of nuxt.config.ts.

export default defineNuxtConfig({
  modules: [
    '@xarenas107/nuxt-socket-io'
  ]
})

Extends socket.io configuration with nuxt hooks.

Hook Argument #Enviroment Description
io:server:config server options server Called before configuring socket.io server
io:server:done socket server server Called after socket.io server initialization
io:config client options client Called before configuring socket.io-client
io:done socket client Called after socket.io-client initialization

Use useSocketIO() or useSocketIOStore() on client side and the useSocketIO() on server side.

// On client side
<script lang='ts' setup>
  const io = useSocketIOStore() // Prevent duplicated listener
  io.on('pong',(message:string) => console.log(message))
  
  await $fetch('/api/ping')
</script>
// On server side
export default defineEventHandler(event => {
  // You can access to io server through `event.context.io` or `useSocketIO().server`
  const io = useSocketIO(event)
  
  const id = io.getId()
  if (id) io.to(id,'pong','Response from server')
  return
})

Or you can create your own methods

// On server side plugin `server/plugins/wss.ts`
export default defineNitroPlugin(nitro => {

  // Add nitro hook
  nitro.hooks.hook('render:response', (response,{ event }) => {
    const { session, user, io } = event.context
    const uid = user?.id || session?.user?.toString()

    // Add connection listener
    if (!event.context.io?.server?.sockets?.adapter?.rooms?.has(uid)) {
      io.server.on('connection', socket => {
        if (!uid) return
        socket.join(uid)
        socket.on('disconnect',() => socket.leave(uid))
      })
    }
  })
})
// On server side middleware `server/middleware/wss.ts`
import type { Server } from 'socket.io'

export default defineEventHandler(event => {
  const { session, user, io } = event.context
  const uid = user?.id || session?.user?.toString()

  event.context.io.emit = (event, message) => {
    return io.server.to(uid).compress(true).emit(event, message)
  }
})

declare module 'h3' {
  interface SocketH3EventContext {
    emit: Server['emit']
  }
}
// On server handler `server/api/chat.post.ts`
export default defineEventHandler(event => {
  const body = await readBody(event)
  
  // Send data to client
  const io = useSocketIO(event)
  io.emit('message', body)

  return null
})

That's it! You can now use @xarenas107/nuxt-socket-io in your Nuxt app ✨