Socket.io implementation in Next.js 14.1.0 app directory

675 Views Asked by At

I want to implement a video conference app where I need to implement socket connection for specific rooms. Since Next.js is a serverless framework, I had to create a default GET method and initialize the socket server and assigning it to NextResponse as a property.

import { NextResponse } from 'next/server';
import { Server } from 'socket.io';

export async function GET(req, res) {
  if (res.socketio) {
    console.log('socket already running');
    return res;
  }
  res = new NextResponse();
  const io = new Server({
    path: '/api/socket.io',
    addTrailingSlash: false,
  });
  io.on('connection', (socket) => {
    console.log('socket id: ', socket.id);
    socket.emit('welcome: ', socket.id);
    socket.on('message', (message) => {
      console.log(message);
    });
    socket.on('disconnect', () => {
      console.log('socket is disconnecting');
    });
  });
  res.socketio = io;
  return res;
}

And calling the io from the client.

'use client';

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

export default function Home() {
  const socket = io();
  const [message, setMessage] = useState('');
  const handleFormSubmit = (e) => {
    e.preventDefault();
    socket.emit('message', message);
  };
  useEffect(() => {
    const fetchIO = async () => await fetch('/api/socket.io');
    fetchIO();
  }, []);
  return (
    <>
      <form onSubmit={handleFormSubmit}>
        <input
          className="border"
          type="text"
          name="message"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        />
        <button type="submit">Submit</button>
      </form>
    </>
  );
}

But the problem I am facing is getting continuous GET 404 not found error.

error sample

Can you please tell me what I am missing? Any suggestion would be appreciated.

I am expecting to read the socket in the client from the server and vice-varsa.

N.B: I want to implement both of client and server functionality on the same server. Thank you :)

0

There are 0 best solutions below