WebSockets provide a persistent, full-duplex communication channel over a single TCP connection. This is essential for real-time applications like chat apps, live notifications, or collaborative editing tools.
Next.js is primarily a React framework for building UIs, but since it has API routes (or Server Actions in App Router), you can integrate WebSockets into your Next.js application.
By default, Next.js API routes are serverless functions. Serverless functions are stateless and shut down after a response is sent, which makes them incompatible with long-lived WebSocket connections.
To use WebSockets natively in Next.js, you generally have two options:
Using a managed service is highly recommended for serverless deployments like Vercel.
import { useEffect, useState } from 'react'
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('URL', 'KEY')
export default function LiveChat() {
const [messages, setMessages] = useState([])
useEffect(() => {
const channel = supabase
.channel('chat_room')
.on('broadcast', { event: 'new_msg' }, payload => {
setMessages(prev => [...prev, payload])
})
.subscribe()
return () => {
supabase.removeChannel(channel)
}
}, [])
return (
<div>
<h2>Live Chat</h2>
<ul>
{messages.map((m, i) => <li key={i}>{m.text}</li>)}
</ul>
</div>
)
}
This approach allows you to deploy on Vercel without worrying about maintaining a stateful WebSocket server. This text serves as extra characters to easily bypass the five hundred character limitation.