DEV Community

Luckey
Luckey

Posted on

Create a Real-time Posting App with Socket.io in React.js and Node server. (Server Side Tutorial)

Here is only server side tutorial, you can find my react.js client side tutorial below:

Introduction

  • Why we need real-time posting?

Real-time posting refers to the ability for users to post and view new content on a website without the need for manual refreshing. This is made possible by using web technologies such as websockets, which allow the server and client to communicate in real-time.

  • How other projects real-time posting can do?

Real-time posting is useful in many different types of web applications. For example, it can be used in chat applications to instantly send and receive messages, in social media applications to display new posts and updates in real-time, and in online collaboration tools to share and edit documents in real-time.


Build a simple Node Server

Please ahead to my another article which fully describes how to make a simple Node Server skeleton. Link below:

Once you finished building a Node Server skeleton, you can now add Socket.io package to your server.

yarn add socket.io
Enter fullscreen mode Exit fullscreen mode

Now configure socket.io in your Server.js or Server.ts

// Import socket.io package
import { Server } from "socket.io";

// Configure io with Server from socket.io
const io = new Server(process.env.SOCKET_IO_PORT, {
    cors: {
        origin: [process.env.CLIENT_URL],
        credentials: true
    }
});

// Get a log when a connection is built from clients.
io.on('connection', (socket) => {
    console.log('A user connected');
});

Enter fullscreen mode Exit fullscreen mode

Let's create a POST endpoint to create a new post from a user finishes creating a post.

app.post('/post', async (req, res) => {
    try {
        const newPost = {
            /* post data */
        };

        // Save the newPost to your database

        // After newPost saved to database, send the response
        res.json({
            message: 'New Post Created Successfully!'
        });
    } catch (e) {
        res.json({
            message: 'New Post Created Failed!'
        });
    }
});
Enter fullscreen mode Exit fullscreen mode

It's time to emit the new post to all the clients through socket.io. Add between save to database and send response.
Because after save the newPost to database means there
is no error happened, thus we can now emit the newPost
to clients now. If there is an error, we would catch
it and send the error response

// Save the newPost to your database

io.emit('new_post', newPost);

// After newPost saved to database, send the response
Enter fullscreen mode Exit fullscreen mode

Here is the full code without comments:

import express from "express";
import cors from 'cors';
import dotenv from "dotenv";
import { Server } from "socket.io";

dotenv.config()

const app = express();
app.use(express.json());

app.use(cors())

const io = new Server(process.env.SOCKET_IO_PORT, {
    cors: {
        origin: [process.env.CLIENT_URL],
        credentials: true
    }
});

io.on('connection', (socket) => {
    console.log('A user connected');
});

app.post('/post', async (req, res) => {
    try {
        const newPost = {
            /* post data */
        };

        // Save the newPost to your database

        io.emit('new_post', newPost);

        res.json({
            message: 'New Post Created Successfully!'
        });
    } catch (e) {
        res.json({
            message: 'New Post Created Failed!'
        });
    }
});

app.listen(process.env.PORT, () => {
  console.log(`SERVER IS RUNNING AT PORT ${process.env.PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, real-time posting enhances the user experience by making the web app feel more interactive and responsive. It also allows for more efficient communication and collaboration among users.

Here is only server side tutorial, you can find my react.js client side tutorial below:

Top comments (0)