Integrating socket.io with your Next.js application

To be able to integrate Next.js with socket.io, you’ll need a next.js app and an external nodeJS server for it. The reason being is that some hosting providers such as vercel or netlify are serverless and won’t allow websocket functionality.

In this …


This content originally appeared on DEV Community and was authored by IroncladDev

To be able to integrate Next.js with socket.io, you'll need a next.js app and an external nodeJS server for it. The reason being is that some hosting providers such as vercel or netlify are serverless and won't allow websocket functionality.

In this example, I'll be using replit for hosting the websocket server and the next.js application. You can do this locally, but make sure both are on different ports!!

First, let's start on the express server. Let's create a new nodeJS repl and start coding in the index.js file.

First, let's require our dependencies.

const express = require("express")
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
  cors: {
    origin: "*" //allowing cors from anywhere
  }
});

Next, we'll set up our express server

app.get("/", (req, res) => {
  res.send("Websocket Server")
})

server.listen(3000, () => {
  console.log('listening on port 3000');
});

And finally, we'll create a very basic websocket input/output handler. Be sure to put this before you run server.listen!

io.on('connection', (socket) => {
  console.log("a user joined!!")
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
  socket.on("chat", (message) => {
    io.emit("chat", message)
  })
});

So basically what the above code does is log whenever a user joins or leaves and emits a message to all clients who are using the chat app when triggered.

Next, let's get our next.js app going. Create a next.js application with npx create-next-app chat-app.

Next (no pun intended), navigate to pages/index.js and install socket.io-client.

We will be declaring a global variable socket and set it to false. I've slapped up a controled input and some state handlers for you already.

import Head from 'next/head'
import {useEffect, useState} from 'react';
import io from 'socket.io-client'

let socket = false;

export default function Home() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");

  const sendMessage = () => {

  }

  return (
    <div>
      <Head>
        <title>Socket.io + Next.js Chat Example</title>
      </Head>
      <h1>Socket.io + Next.js chat example</h1>
      <input placeholder="message" onChange={e => setInput(e.target.value)} value={input}/><button onClick={sendMessage}>send</button>
      <div id="messages">{messages.map(msg => <div className="message">{msg}</div>)}</div>
    </div>
  )
}

In our component, let's get a useEffect handler open. In this hook, we will be assigning and connecting our socket to the websocket server. Simply put the url of the socket server into the io function.

useEffect(() => {
    if(!socket){
        socket = io("https://SocketServer.ironcladdev.repl.co");
    }
}, [])

Next, let's create another useEffect hook in our component. The reason why we'll have two is because we need to ensure the component runs the second useEffect hook each time the messages state updates.

useEffect(() => {
    socket.on("chat", (msg) => {
        setMessages([...messages, msg])
    })
}, [messages]);

Finally, let's make it so that you can send messages and complete our sendMessage function.

const sendMessage = () => {
    socket.emit("chat", input);
    setInput("");
}

Now we are done!

I apoligize for the zero CSS I used. That's why I don't write much on it.

Next.js chat app source code

Node.js websocket server

Liked this? Be sure to subscribe to me at my website and join my discord server.

Happy Coding y'all :)


This content originally appeared on DEV Community and was authored by IroncladDev


Print Share Comment Cite Upload Translate Updates
APA

IroncladDev | Sciencx (2022-02-09T20:51:55+00:00) Integrating socket.io with your Next.js application. Retrieved from https://www.scien.cx/2022/02/09/integrating-socket-io-with-your-next-js-application/

MLA
" » Integrating socket.io with your Next.js application." IroncladDev | Sciencx - Wednesday February 9, 2022, https://www.scien.cx/2022/02/09/integrating-socket-io-with-your-next-js-application/
HARVARD
IroncladDev | Sciencx Wednesday February 9, 2022 » Integrating socket.io with your Next.js application., viewed ,<https://www.scien.cx/2022/02/09/integrating-socket-io-with-your-next-js-application/>
VANCOUVER
IroncladDev | Sciencx - » Integrating socket.io with your Next.js application. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/09/integrating-socket-io-with-your-next-js-application/
CHICAGO
" » Integrating socket.io with your Next.js application." IroncladDev | Sciencx - Accessed . https://www.scien.cx/2022/02/09/integrating-socket-io-with-your-next-js-application/
IEEE
" » Integrating socket.io with your Next.js application." IroncladDev | Sciencx [Online]. Available: https://www.scien.cx/2022/02/09/integrating-socket-io-with-your-next-js-application/. [Accessed: ]
rf:citation
» Integrating socket.io with your Next.js application | IroncladDev | Sciencx | https://www.scien.cx/2022/02/09/integrating-socket-io-with-your-next-js-application/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.