Next.js Discord

Discord Forum

nextJs socket.io message app

Unanswered
Checkered Giant posted this in #help-forum
Open in Discord
Checkered GiantOP
Hi there!
i'm coding a project in nextJs in ts with socket.io to make a live messaging system.
i have one or two questions about the structure to have if people know about it

For the socket I use socket.io but I have the impression that my code isn't very clean, in the current operation in each page I fetch my api/socket to the page load and I initiate each event in each page then I set my socket.
Do you know how to do this and what to use to be able to just call the socket with all the events directly with a kind of provider?

Thanks a lot!

113 Replies

Did you try creating a client side provider and wrapping your app in that provider?
I think that should resolve the issue
@shor Did you try creating a client side provider and wrapping your app in that provider?
Checkered GiantOP
you allready have used nextjs with socketio?
i tryed that a long time ago but cant make it work
@Checkered Giant you allready have used nextjs with socketio?
no i've not, I have used it recently with my react app, I had my socket in a context and I was using the socket from that context only
Checkered GiantOP
yep but how did you wrap a socket in a context?
because btw with react your socket is in an server file no?
with nextJs thats in an api
so idk
Checkered GiantOP
but if you think that can work why not try
@Checkered Giant with nextJs thats in an api
you might wanna create a custom backend server for socket, cause serverless functions on vercel are quite expensive
Try creating a socket provider wrap your app in it, that should fix the issue
@shor you might wanna create a custom backend server for socket, cause serverless functions on vercel are quite expensive
Checkered GiantOP
mmhhh an socket api seems work and from the tutorial ect i've seen that seems going right
@shor https://alexboots.medium.com/using-react-context-with-socket-io-3b7205c86a6d
Checkered GiantOP
i will check and tell you, thx
✌🏾.
@shor ✌🏾.
Checkered GiantOP
btw did you ever used socketio with nextjs?, my request often call twice
no I haven't
@Checkered Giant btw did you ever used socketio with nextjs?, my request often call twice
ahh okay, i'm afraid my solution wasn't helpful
@shor ahh okay, i'm afraid my solution wasn't helpful
Checkered GiantOP
nahhh not at all any connection with your solution
thats another issue that i have
but for you solution i will try a soon as u ca
can*
you should check when do you wanna emit events, like the useEffect effects are setup correctly
you can also share code snippets, that'll allow ppl to help you better
@shor you should check when do you wanna emit events, like the useEffect effects are setup correctly
Checkered GiantOP
yes, but i think that my issue come from that my api socketIo is fetch multiple time
i fetch it in my useffect
useEffect(()=>{
        if(!router.isReady) return;

        if(user){
          console.log('aa')
          fetchRoom()
          socketInitializer()
        }
    },[router.isReady,session])

and i think that my router call it multiple time
so idk how to call it only after that the router is ready and only one time
does this happen in the deployed version as well?
@shor does this happen in the deployed version as well?
Checkered GiantOP
mhh i dont deployed my project since i created it
i only dev in localhost for now
did you thing i should deploy it?
yeah deploy it in vercel and check if the issues persist
Checkered GiantOP
yup but to deploy on vercel i first need to fix all ts issue ahah
@shor https://rishabhsharma.bio/next-js-issue-useeffect-hook-running-twice-in-client-9fb6712f6362#:~:text=When%20using%20React%E2%80%99s,your%20production%20build
Checkered GiantOP
oohhh okay, i switched the "reactStrictMode: false" and that seems to work well
I don't think that is ideal though
but if its necessary for testing purpose then why not
@shor but if its necessary for testing purpose then why not
Checkered GiantOP
why?, and btw its not like a profesional project, more like some test with socket
@shor its mentioned there in the article
Checkered GiantOP
ok thx
can i step into the conversation
whats the core problem
or is it already solved
@gin or is it already solved
Checkered GiantOP
nah its not
the code probleme is the first message
"
Hi there!
i'm coding a project in nextJs in ts with socket.io to make a live messaging system.
i have one or two questions about the structure to have if people know about it

For the socket I use socket.io but I have the impression that my code isn't very clean, in the current operation in each page I fetch my api/socket to the page load and I initiate each event in each page then I set my socket.
Do you know how to do this and what to use to be able to just call the socket with all the events directly with a kind of provider?

Thanks a lot!
"
just
make a clientside component that exposed a instance of ur socket
and put that into ur root layout
or ur parent component
that wraps ur chat
Checkered GiantOP
mhhh yep but how did i access to my socket.emit in a page?
u can do it in two ways
@gin u can do it in two ways
Checkered GiantOP
how?
u have a getter function that u can use for ur singleton instance
or
u have functions that initate and returns ur socket whenever a message is fired from backend
public async requestRTC(id: string, fromId: string, callbackAnswer: (msg: any) => void) {
    this.socket.emit("requestRTC", id, fromId);

    this.socket.on("answerRTC", (msg: any) => {
      callbackAnswer(msg);
    });
  }
Checkered GiantOP
mmhhh not sure to understand what is it
@gin
what is what
u dont understand what im telling u?
code is just a example
im just telling u the concept
Checkered GiantOP
mmhhh yep but wdym a public function?
i do not understand what did you said
u dont now what public functions are?
if u create a new instance of a class u can access the public functions externally
instance can be a init using a singleton
so if u call getInstance for example we make sure u dont have multiples of it
@gin so if u call getInstance for example we make sure u dont have multiples of it
Checkered GiantOP
@gin i never see an public function in nextJs 😅
thats typescript brother
Checkered GiantOP
wdym?
@gin https://www.typescriptlang.org/docs/
Checkered GiantOP
i know typescript, but not public func
and i dont see what typescript can be usefull for socketio
@Checkered Giant i know typescript, but not public func
then u dont know typescript
Checkered GiantOP
so can u explain?
i did
idk how to explain more
u can understand that im sure
u have a component that u put in a wrapper, parent or in ur root
that components has a class where ur instance of ur socket is
u call getInstance in ur chat or idk
u can then use that instance accross ur nextjs app
thats the purpose of classes in typescript
@gin thats the purpose of classes in typescript
Checkered GiantOP
so if i setup that after that i will call classes in my page and this classes will got a proprety like socket or something like that?
Checkered GiantOP
did you have an exemple of what ur explaining?
ask chatgpt
Checkered GiantOP
okk thx
i will check that as soon as i can
@Checkered Giant okk thx
hold on
export class Socket {
  private static instance: Socket;
  private socket: any;

  public static getInstance(): Socket {
    if (!Socket.instance) {
      Socket.instance = new Socket();
    }
    return Socket.instance;
  }

  public getSocket(): any {
    return this.socket;
  }
}
something like this
Checkered GiantOP
okay, but my socket is an api, so i replace "new Socket" by a fetch of my api?
private constructor() {
    this.socket = io("https://yourapi/", {
      path: "/api/socket.io",
    });
  }
u mean that probably
ok
@gin ok
Checkered GiantOP
sry i left without responding u, i mean that i get my socket with liek const data = fetch('http://localhost:3000/api/socket')
if u are using socket.io read the docs again
@gin if u are using socket.io read the docs again
Checkered GiantOP
socketio is not make for nextjs so the doc dont talk 'bout it
@gin this is correct
Checkered GiantOP
mmhhh ok but where did i use it and how did i call my socket?