Use router outside component
Unanswered
Brown bear posted this in #help-forum
Brown bearOP
Hi, I'm having a websocket connection in my Nextjs app (and btw I'm new to next so I don't know everything). My problem is that I have an event in this websocket where I would like to redirect the user to my home page. I already searched on the internet but couldn't find how to use router outside a component. Could someone help me please?
4 Replies
Boston Terrier
How are you handling the websocket connections?
You can't use hooks outside components. They are tied to a component's life cycle and
If you need to redirect the user you can do it on client side with [
useRouter is a hook.If you need to redirect the user you can do it on client side with [
redirect](https://nextjs.org/docs/app/api-reference/functions/redirect) or on server side with [NextResponse.redirect()](https://nextjs.org/docs/app/api-reference/functions/next-response#redirect)@Boston Terrier How are you handling the websocket connections?
Brown bearOP
The websocket connection is stored through a variable exported in a ts file. I finally managed to do something with useContext and I created a component called WebSocketProvider so I can wrap components that need websocket connection and calling useWebSocket
(btw I'm not English native so I may make spelling errors)