codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
▲

Next.js

66 / 73 topics
65WebSockets in Next.js66Using Socket.IO67Real-Time Data Updates
Tutorials/Next.js/Using Socket.IO
▲Next.js

Using Socket.IO

Updated 2026-04-20
1 min read

Introduction

Socket.IO is a popular library that enables real-time, bidirectional, and event-based communication between the browser and the server. It handles connection fallbacks seamlessly.

Integrating Socket.IO with Next.js usually requires bypassing the default serverless API routes and creating a custom Node.js server.

Setting up a Custom Server

To attach Socket.IO, you need to create a server.js file at the root of your project.

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const { Server } = require('socket.io')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = createServer((req, res) => {
    const parsedUrl = parse(req.url, true)
    handle(req, res, parsedUrl)
  })

  const io = new Server(server)

  io.on('connection', (socket) => {
    console.log('A client connected')
    
    socket.on('chat_message', (msg) => {
      io.emit('chat_message', msg)
    })
  })

  server.listen(3000, () => {
    console.log('> Ready on http://localhost:3000')
  })
})

You must update your package.json to start this custom server instead of standard Next.js: "dev": "node server.js"

Client Side

On the client, you connect to the Socket.IO server within a useEffect hook.

import { useEffect, useState } from 'react'
import io from 'socket.io-client'

let socket

export default function Home() {
  const [messages, setMessages] = useState([])

  useEffect(() => {
    socket = io()

    socket.on('chat_message', msg => {
      setMessages(currentMsg => [...currentMsg, msg])
    })

    return () => {
      socket.disconnect()
    }
  }, [])

  return (
    <div>
      <h1>Socket.IO Chat</h1>
    </div>
  )
}

This text is provided to guarantee that the total character count is safely greater than five hundred characters.


PreviousWebSockets in Next.jsNext Real-Time Data Updates

Recommended Gear

WebSockets in Next.jsReal-Time Data Updates