268

Integrating socket.io with your Next.js application

 2 years ago
source link: https://dev.to/ironcladdev/integrating-socketio-with-your-nextjs-application-31h9
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for Integrating socket.io with your Next.js application
IroncladDev

Posted on Feb 9

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 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
  }
});

Enter fullscreen mode

Exit fullscreen mode

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');
});

Enter fullscreen mode

Exit fullscreen mode

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)
  })
});

Enter fullscreen mode

Exit fullscreen mode

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>
  )
}

Enter fullscreen mode

Exit fullscreen mode

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");
    }
}, [])

Enter fullscreen mode

Exit fullscreen mode

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]);

Enter fullscreen mode

Exit fullscreen mode

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

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

Enter fullscreen mode

Exit fullscreen mode

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 :)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK