Create a Real-time Posting App with Socket.io in React.js and Node server. (Server Side Tutorial)
Tags: react, node, webdev, javascript
Published: 2022-12-16 01:30:28

**_Here is only server side tutorial, you can find my react.js client side tutorial below:_**
{% embed https://dev.to/luckey/create-a-real-time-posting-app-with-socketio-in-reactjs-and-node-server-client-side-tutorial-188a %}

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

{% embed https://dev.to/luckey/create-a-simple-node-server-skeleton-1m2i %}


> Once you finished building a Node Server skeleton, you can now add [Socket.io](https://socket.io/) package to your server.

```
yarn add socket.io
```

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

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

```

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

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

> 
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

```javascript
// Save the newPost to your database

io.emit('new_post', newPost);

// After newPost saved to database, send the response
```

## Here is the full code without comments:

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

---
## 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:_**
{% embed https://dev.to/luckey/create-a-real-time-posting-app-with-socketio-in-reactjs-and-node-server-client-side-tutorial-188a %}