NextJS socket.io
/*
Install SocketIO for Creating Server
npm i socket.io
Install SocketIO-Client for Creating Client
npm i socket.io-client
*/
// Socket Server
// 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
// --------------------------------------------------
// Socket Client
// pages/home.js -----------------------------------
import { useEffect, useState } from 'react'
import io from 'socket.io-client'
let socket;
const Home = () => {
const [input, setInput] = useState('')
useEffect(() => {
socketInitializer();
return () => {
console.log("This will be logged on unmount");
}
})
const socketInitializer = async () => {
await fetch('/api/socket');
socket = io()
socket.on('connect', () => {
console.log('connected')
})
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;
// ----------------------------------------------
tam11a