添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

// Tutorial //

How To Use Server-Sent Events in Node.js to Build a Realtime App

Published on November 18, 2019 · Updated on March 22, 2021
Default avatar

By Sebastián Alvarez

How To Use Server-Sent Events in Node.js to Build a Realtime App

Introduction

WebSockets .

In this article, you will build a complete solution for both the backend and frontend to handle real-time information flowing from server to client. The server will be in charge of dispatching new updates to all connected clients and the web app will connect to the server, receive these updates and display them.

Prerequisites

  • How to Install Node.js and Create a Local Development Environment .
  • Familiarity with Express.
  • Familiarity with React (and hooks ).
  • cURL is used to verify the endpoints. This may already be available in your environment or you may need to install it. Some familiarity with using command-line tools and options will also be helpful.
  • This tutorial was verified with cURL v7.64.1, Node v15.3.0, npm v7.4.0, express v4.17.1, body-parser v1.19.0, cors v2.8.5, and react v17.0.1.

    Step 1 – Building the SSE Express Backend

              1. stringify the array, also to fulfill the standard the message needs a specific format. This code declares a field called data and sets to it the stringified array. The last detail of note is the double trailing newline \n\n is mandatory to indicate the end of an event.

                A clientId is generated based on the timestamp and the response Express object. These are saved to the clients array. When a client closes a connection, the array of clients is updated to filter out that client.

                Then, build the middleware for POST requests to the /fact endpoint. Add the following lines of the code to server.js:

                sse-server/server.js

                Step 2 – Testing the Backend

                              1. Step 3 – Building the React Web App Frontend

                              2. create-react-app to generate a React App.

                                    1. Step 4 – Testing the Frontend

                                      1. Conclusion

                                        current support for EventSource in browsers.

                                        Continue your learning by exploring all of the features available to EventSource like retry.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about us


    About the authors
    Default avatar
    Sebastián Alvarez

    author

    Still looking for an answer?

    Ask a question Search for more help

    Was this helpful?
    10 Comments
    

    This textbox defaults to using Markdown to format your answer.

    You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

    for those who are in the TLDR category, I put a repo of the working code here, i changed port 3001 to 3000 https://github.com/bradenripple5/node-sse-example

    bkoprivica January 3, 2023

    “After the POST request, the second terminal window should update with the new fact”

    It should but it doesn’t. The list remain empty

    The provided example is just too trivial and can’t be directly applied to any real production application. What if you have multiple server instances and a load-balancer? What if you need to send events from server-side workers?

    satinet June 14, 2022

    If you’re seeing double connections from the client, that’s useEffect running twice because of React Strict mode, which is on in dev by default

    StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).

    You can remove the strict mode tags from index.js.

    This comment has been deleted

    mikiskela90 January 14, 2022

    This comment has been deleted

    How this exact example can be done if node application has more than 1 process. Let’s say that application works in pm2 cluster mode.

    Correct me if I’m missing something, but it seems that async and next should both be removed from the addFact() declaration because there is no await nor next() within the function.

    bodyParser is now deprecated and its functionality is now included in Express, so the require(‘body-parser’) line needs to be deleted and these lines:

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));
    

    Change to:

    app.use(express.json());
    app.use(express.urlencoded({extended: false}));
    

    Also the listen port is set to 3000, but all the port references after that are 3001.

    And there’s a typo re: respsonse in function addFact.