Mandeep Singh
Mandeep Singh Blog

Mandeep Singh Blog

WebSocket chat in Next.js

WebSocket chat in Next.js

Mandeep Singh's photo
Mandeep Singh
·May 5, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article
npx create-next-app chat-app

Setup websocket

npm install socket.io

create > socket.io file in > pages/api/

// socket.js
import { Server } from 'Socket.IO'

const SocketHandler = (req, res) => {
  if (res.socket.server.io) {
    console.log('Socket is already running')
  } else {
    console.log('Socket is initializing')
    const io = new Server(res.socket.server)
    res.socket.server.io = io

    io.on('connection', socket => {
      socket.on('input-change', msg => {
        socket.broadcast.emit('update-input', msg)
      })
    })
  }
  res.end()
}

export default SocketHandler

replace index.js file with

// index.js

import { useEffect, useState } from 'react'
import io from 'Socket.IO-client'
let socket;

const Home = () => {
  const [input, setInput] = useState('')

  useEffect(() => socketInitializer(), [])

  const socketInitializer = async () => {
    await fetch('/api/socket');
    socket = io()

    socket.on('connect', () => {
      console.log('connected mm')
    })

    socket.on('update-input', msg => {
      setInput(msg)
    })
  }

  const onChangeHandler = (e) => {
    setInput(e.target.value)
    socket.emit('input-change', e.target.value)
  }

  return (
    <input
      placeholder="Type something"
      value={input}
      onChange={onChangeHandler}
    />
  )
}

export default Home;

Result

socket-updating-realtime.gif

 
Share this