Demo app of React Server Components.

Overview

React Server Components Demo

What is this?

This is a demo app built with Server Components, an experimental React feature. We strongly recommend watching our talk introducing Server Components before exploring this demo. The talk includes a walkthrough of the demo code and highlights key points of how Server Components work and what features they provide.

When will I be able to use this?

Server Components are an experimental feature and are not ready for adoption. For now, we recommend experimenting with Server Components via this demo app. Use this in your projects at your own risk.

Setup

You will need to have nodejs >=14.9.0 in order to run this demo. Node 14 LTS is a good choice!

npm install
npm start

(Or npm run start:prod for a production build.)

Then open http://localhost:4000.

The app won't work until you set up the database, as described below.

Setup with Docker (optional)

You can also start dev build of the app by using docker-compose.

⚠️ This is completely optional, and is only for people who prefer Docker to global installs!

If you prefer Docker, make sure you have docker and docker-compose installed then run:

docker-compose up

Running seed script

1. Run containers in the detached mode

docker-compose up -d

2. Run seed script

docker-compose exec notes-app npm run seed

If you'd rather not use Docker, skip this section and continue below.

DB Setup

This demo uses Postgres. First, follow its installation link for your platform.

Alternatively, you can check out this fork which will let you run the demo app without needing a database. However, you won't be able to execute SQL queries (but fetch should still work). There is also another fork that uses Prisma with SQLite, so it doesn't require additional setup.

The below example will set up the database for this app, assuming that you have a UNIX-like platform:

Step 1. Create the Database

psql postgres

CREATE DATABASE notesapi;
CREATE ROLE notesadmin WITH LOGIN PASSWORD 'password';
ALTER ROLE notesadmin WITH SUPERUSER;
ALTER DATABASE notesapi OWNER TO notesadmin;
\q

Step 2. Connect to the Database

psql -d postgres -U notesadmin;

\c notesapi

DROP TABLE IF EXISTS notes;
CREATE TABLE notes (
  id SERIAL PRIMARY KEY,
  created_at TIMESTAMP NOT NULL,
  updated_at TIMESTAMP NOT NULL,
  title TEXT,
  body TEXT
);

\q

Step 3. Run the seed script

Finally, run npm run seed to populate some data.

And you're done!

Notes about this app

The demo is a note-taking app called React Notes. It consists of a few major parts:

  • It uses a Webpack plugin (not defined in this repo) that allows us to only include client components in build artifacts
  • An Express server that:
    • Serves API endpoints used in the app
    • Renders Server Components into a special format that we can read on the client
  • A React app containing Server and Client components used to build React Notes

This demo is built on top of our Webpack plugin, but this is not how we envision using Server Components when they are stable. They are intended to be used in a framework that supports server rendering — for example, in Next.js. This is an early demo -- the real integration will be developed in the coming months. Learn more in the announcement post.

Interesting things to try

  • Expand note(s) by hovering over the note in the sidebar, and clicking the expand/collapse toggle. Next, create or delete a note. What happens to the expanded notes?
  • Change a note's title while editing, and notice how editing an existing item animates in the sidebar. What happens if you edit a note in the middle of the list?
  • Search for any title. With the search text still in the search input, create a new note with a title matching the search text. What happens?
  • Search while on Slow 3G, observe the inline loading indicator.
  • Switch between two notes back and forth. Observe we don't send new responses next time we switch them again.
  • Uncomment the fetch('http://localhost:4000/sleep/....') call in Note.server.js or NoteList.server.js to introduce an artificial delay and trigger Suspense.
    • If you only uncomment it in Note.server.js, you'll see the fallback every time you open a note.
    • If you only uncomment it in NoteList.server.js, you'll see the list fallback on first page load.
    • If you uncomment it in both, it won't be very interesting because we have nothing new to show until they both respond.
  • Add a new Server Component and place it above the search bar in App.server.js. Import db from db.server and use db.query() from it to get the number of notes. Oberserve what happens when you add or delete a note.

You can watch a recorded walkthrough of all these demo points here (with timestamps).

Built by (A-Z)

Code of Conduct

Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.

License

This demo is MIT licensed.

Comments
  • docker doesn't work

    docker doesn't work

    image `postgres_1 | /usr/local/bin/docker-entrypoint.sh: sourcing /docker-entrypoint-initdb.d/init_db.sh postgres_1 | 2020-12-22 06:31:21.349 UTC [70] ERROR: role "notesadmin" already exists postgres_1 | 2020-12-22 06:31:21.349 UTC [70] STATEMENT: CREATE ROLE notesadmin WITH LOGIN PASSWORD 'password'; postgres_1 | ERROR: role "notesadmin" already exists`
    opened by ynifamily3 8
  • Failed to build

    Failed to build

    Windows 10, Node 15.4.0, NPM 7.0.15

    [0] Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: server-components-demo\node_modules\@babel\runtime\helpers\esm\createForOfIteratorHelper.js
    [0] require() of ES modules is not supported.
    [0] require() of server-components-demo\node_modules\@babel\runtime\helpers\esm\createForOfIteratorHelper.js from server-components-demo\node_modules\marked\src\marked.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
    [0] Instead rename createForOfIteratorHelper.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from server-components-demo\node_modules\@babel\runtime\helpers\esm\package.json.
    [0]
    [0]     at new NodeError (node:internal/errors:278:15)
    [0]     at Module._extensions..js (node:internal/modules/cjs/loader:1125:13)
    [0]     at Object.newLoader [as .js] (server-components-demo\node_modules\pirates\lib\index.js:104:7)
    [0]     at Module.load (node:internal/modules/cjs/loader:973:32)
    [0]     at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    [0]     at Module.require (node:internal/modules/cjs/loader:997:19)
    [0]     at require (node:internal/modules/cjs/helpers:92:18)
    [0]     at Object.<anonymous> (server-components-demo\node_modules\marked\src\marked.js:5:58)
    [0]     at Module._compile (node:internal/modules/cjs/loader:1108:14)
    [0]     at Module._compile (server-components-demo\node_modules\pirates\lib\index.js:99:24) {
    [0]   code: 'ERR_REQUIRE_ESM'
    [0] }
    
    opened by Jack-Works 8
  • Failed to compile on windows

    Failed to compile on windows

    Windows 10, Node 14.9.0, npm 6.14.8

    TypeError: D:\Projects\personal\server-components-demo\node_modules\safe-buffer\index.js: Cannot read property 'from' of undefined
        at Converter.toBase64 (D:\Projects\personal\server-components-demo\node_modules\convert-source-map\index.js:61:28)
        at Converter.toComment (D:\Projects\personal\server-components-demo\node_modules\convert-source-map\index.js:65:21)
        at generateCode (D:\Projects\personal\server-components-demo\node_modules\@babel\core\lib\transformation\file\generate.js:78:76)
        at run (D:\Projects\personal\server-components-demo\node_modules\@babel\core\lib\transformation\index.js:55:33)
        at run.next (<anonymous>)
        at Function.transform (D:\Projects\personal\server-components-demo\node_modules\@babel\core\lib\transform.js:27:41)
        at transform.next (<anonymous>)
        at evaluateSync (D:\Projects\personal\server-components-demo\node_modules\gensync\index.js:251:28)
        at Function.sync (D:\Projects\personal\server-components-demo\node_modules\gensync\index.js:89:14)
        at Object.transform (D:\Projects\personal\server-components-demo\node_modules\@babel\core\lib\transform.js:36:54) {
      code: 'BABEL_GENERATE_ERROR'
    }
    
    opened by sam17896 7
  • RSC webpack 5 plugin

    RSC webpack 5 plugin

    get the same plugin from react-server-dom-webpack to be compatible with webpack 5

    • write it in TypeScript so I can make use of typing to find webpack internal interface
    • build-old is the old assets the webpack 4 version of plugin produce
    • to build, run npm run bundler:dev
    • all the changes in plugins/react-server-dom-webpack-plugin.ts
    • eventually upstream plugins/react-server-dom-webpack-plugin.js
    opened by michenly 4
  • SSR

    SSR

    👋 I wanted to familiarize a bit with the SC JSON format and I implemented a rudimentary and very naive SSR renderer with a transform stream that sits in between React's stream and res (the response) and turns React's Server Components JSON into HTML.

    I made this "feature" opt-in and you need to set the ssr query param to get SSR eg. http://localhost:4000/?ssr

    I was wondering if this is how you'd imagine SSR to work with Server Components or you'd rather do classic, old style SSR with renderToStaticNodeStream and send the server components JSON payload to do hydration?

    PS. as I mentioned at the beginning this was just an exercise, the approach might be completely wrong so I don't expect to see this PR merged at any cost (I am just trying to learn something new :)

    opened by giuseppeg 4
  • fix: JSON.parse fails in react-fetch

    fix: JSON.parse fails in react-fetch

    JSON.parse fails in react-fetch

    JSON.parse (empty data) doesn't work properly when I get empty data. In react-fetch, I get Uncaught Syntax Error.

    fetch(`http://localhost:4000/notes/-1`)
    
    • api.server.js
      • GET: /notes/:id

    res.json(rows[0]);

    Just escape it like this

    res.json(rows[0] || "null");
    

    https://stackoverflow.com/questions/9158665/json-parse-fails-in-google-chrome

    opened by rgbkids 3
  • How does react decide to rerender search result?

    How does react decide to rerender search result?

    First of all, thank you for a great example 🙂️. And thank you for keeping in touch with what React dev team is working on. That's a great thing!

    For example, when I create a new note with the title test and I already have search input with test, how react decide that the search result should be rerendered on the server? This thing is not clear to me 🤔️

    opened by quolpr 3
  • server: use fs.promises instead of fs/promises

    server: use fs.promises instead of fs/promises

    With this change, as well as a change to react-fs, this repo will be able to support Node.js 12 (tested locally).

    I can't seem to find the repo for react-fs though to propose the change ¯\_(ツ)_/¯

    opened by MylesBorins 3
  • Add eslint config

    Add eslint config

    Hi,

    I know it's a demo but it probably wouldn't harm us to set up eslint. :slightly_smiling_face:

    I fixed a few minor warnings/errors. Fixes for two other that left are in #22.

    opened by micorix 3
  • Setup: Node v14 is required

    Setup: Node v14 is required

    With Node v12, I get the error "Error: Cannot find module 'fs/promises'" With Node v13, the server is not running, "node: bad option: --conditions=react-server" in the logs.

    Fixed with Node v14.

    opened by arnaudbzn 3
  • error: password authentication failed for user

    error: password authentication failed for user "notesadmin"

    I cloned the repo, and ran npm install When I access localhost:4000 I get the following error: error: password authentication failed for user "notesadmin"

    opened by dugiwarc 2
  • Set babel config to use commonjs modules on server

    Set babel config to use commonjs modules on server

    Fixes #60

    Previously, if you had

    export default function App({
      selectedId,
      isEditing,
      searchText,
      something = ['a', 'b'],
    }) {
      const [a, b] = something;
      console.log(a, b);
    

    this would error with

    internal/modules/cjs/loader.js:1102
          throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
          ^
    
    Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /rsc/server-components-demo/node_modules/@babel/runtime/helpers/esm/slicedToArray.js
    require() of ES modules is not supported.
    

    This updates the babel config on the server to use useESModules: false

    opened by penx 0
  • Can't use destructuring assignment in server code

    Can't use destructuring assignment in server code

    As mentioned (in more detail) at https://github.com/facebook/react/issues/23126#issuecomment-1301880271

    If you use destructuring assignment in a server component, you get a babel error:

    /server-components-demo/src/App.server.js:141
    undefined
          ^
    
    Error [ERR_REQUIRE_ESM]: require() of ES Module /server-components-demo/node_modules/@babel/runtime/helpers/esm/slicedToArray.js from /server-components-demo/src/App.server.js not supported.
    Instead change the require of slicedToArray.js in /server-components-demo/src/App.server.js to a dynamic import() which is available in all CommonJS modules.
    
    opened by penx 0
  • fix: JSON.parse fails in react-fetch

    fix: JSON.parse fails in react-fetch

    From: https://github.com/reactjs/server-components-demo/pull/50

    gaearon commented 11 hours ago why is the data empty?

    gaearon commented 6 hours ago i'll close because it's not supposed to be empty. if there's some case where it's empty let's figure out why.


    About empty data: We are testing the RSC demo as a team.

    I got a SyntaxError when testing with two people. The operation is as follows.

    • Operations

    | User | | |:----:|:----:| | Operation 1 (User-A): User-A show the initial page. | 01_Operator-A_01 | | Operation 2 (User-B): User-B show the initial page. | 02_Operator-B_01 | | Operation 3 (User-B): User-B delete the first record. | 03_Operator-B_02 | | Operation 4 (User-B): User-B finished deleting the first record. | 04_Operator-B_03 | | Operation 5 (User-A): The first record is still visible on the screen of User-A. | 05_Operator_A_02 | | Operation 6 (User-A): An error occurs when User-A taps the first record. | 06_Operator_A_03 |

    • Operation 6 (User-A): An error occurs when User-A taps the first record.

    The logs are as follows.

    Application Error
    SyntaxError: Unexpected end of JSON input
        at JSON.parse (<anonymous>)
        at Response.json (/opt/notes-app/node_modules/react-fetch/cjs/react-fetch.node.development.js:133:21)
        at Note (/opt/notes-app/src/Note.server.js:65:60)
        ...
    

    When I looked into it, I found the cause of the error in react-fetch.

    • react-fetch.node.development.js
      json: function () {
        if (this._json !== null) {
          return this._json;
        }
    
        var buffer = readRecordValue(this._bufferRecord);
        var json = JSON.parse(buffer.toString());
        this._json = json;
        return json;
      },
    

    Passing an empty character to JSON.parse will cause a SyntaxError.

    let json1 = JSON.parse(""); // => SyntaxError
    let json2 = JSON.parse([]); // => SyntaxError
    let json3 = JSON.parse(null); // OK
    let json4 = JSON.parse("null"); // OK
    

    The problem is that the caller of react-fetch cannot catch SyntaxError. The application will go down before I can catch it.

    For example:

      try {
        let result = fetch(`http://localhost:4000/notes/${selectedId}`);
        console.log(result);  // => ERROR:  invalid input syntax for type integer: "null"  STATEMENT:  select * from notes where id = $1
      } catch (error) {
        // SyntaxError is not caught.
        console.log(error);
      }
    

    So we proposed a change in api.server.js.

    • api.server.js
      • GET: /notes/:id

    res.json(rows[0]);

    Just escape it like this

    res.json(rows[0] || null);
    

    This way, the caller of react-fetch can make the decision. Note.server.js does not need to be changed.

    opened by rgbkids 0
  • SyntaxError: Cannot use import statement outside a module

    SyntaxError: Cannot use import statement outside a module

    Run after installed dependencies met such error:

    import React,{Suspense} from 'react';
    ^^^^^^
    
    SyntaxError: Cannot use import statement outside a module
    
    opened by futurechallenger 0
Owner
React Community
React website and its localizations
React Community
Server Side render your interactive React Gutenberg blocks

Block Editor SSR Server Side render your interactive React Gutenberg blocks. A Human Made project. Maintained by @joehoyle. Block Editor SSR adds supp

Human Made 31 Nov 17, 2022
:rocket: A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server

Apollo Client Apollo Client is a fully-featured caching GraphQL client with integrations for React, Angular, and more. It allows you to easily build U

Apollo GraphQL 18.3k Jan 1, 2023
:recycle: React integration for Apollo Client

React Apollo ⚠️ THIS PROJECT HAS BEEN DEPRECATED ⚠️ Please note that 4.0.0 is the final version of all React Apollo packages. React Apollo functionali

Apollo GraphQL 6.9k Jan 7, 2023
Relay is a JavaScript framework for building data-driven React applications.

Relay · Relay is a JavaScript framework for building data-driven React applications. Declarative: Never again communicate with your data store using a

Facebook 17.5k Dec 28, 2022
A Socket.io / React Js real time multiplayer flash card game for learning.

A Socket.io / React Js real time multiplayer flash card game for learning.

John Doe 18 Sep 17, 2022
React Socket.io Online Multiplayer Tic-Tac-Toe Game created on CoderOne youtube video

Tic Tac Toe Online Multiplayer Game Youtube Video https://youtu.be/aA_SdbGD64E What we will cover? Socket.io for absolute beginners ?? Socket.io Rooms

Islem Maboud 42 Jan 6, 2023
A demo app of the Hacker News website clone, which shows Next.js 12's experimental React Server Components support

A demo app of the Hacker News website clone, which shows Next.js 12's experimental React Server Components support

Vercel 681 Jan 6, 2023
Next.js 12 React Server Components Demo

Next.js 12 React Server Components Demo This is the demo of Hacker News built with Next.js and React Server Components. Read our announcement here: Ne

Vercel 678 Dec 27, 2022
Experimental demo of React Server Components with Next.js. Deployed serverlessly on Vercel.

React Server Components in Next.js Experimental app of React Server Components with Next.js, based on React Server Components Demo. It's not ready for

Vercel 676 Jan 4, 2023
React 18 Beta (Suspense, concurrent rendering, HTTP streaming, Server Components) + Next.js 12.0.4 demo & benchmark (performance & UX)

Next.js 12.0.4 and React 18 Beta Demo & Benchmark Next.js 12 comes with React 18 Beta support. React 18 will add features like Suspense, automatic bat

Cedric Chee 4 Jun 20, 2022
Vercel 675 Dec 28, 2022
Animo-demo - Animo Self-Sovereign Identity Demo build using Aries Framework Javascript

Animo Self-Sovereign Identity Demo ✨ Hi there! Welcome to the repository of Anim

Animo 14 Dec 7, 2022
Club-Event-Calendar-Webpage-Demo - Webpage Demo for Club Event Calendar

Club Event Calendar Webpage Demo Demo Repository for Club Event Calendar Webpage

Hyecheol (Jerry) Jang 1 Jan 9, 2022
Barton Hammond 4.6k Dec 29, 2022
Barton Hammond 4.6k Jan 2, 2023
Webapp of Mattermost server: https://github.com/mattermost/mattermost-server

Mattermost Mattermost is an open source, self-hosted Slack-alternative from https://mattermost.org. It's written in Golang and React and runs as a sin

Mattermost 2.2k Jan 4, 2023
Server Authentication with JWT - Server authentication, prevent render before validation.

Server authentication on Next.js using JWT it works with node version 7.8.0 or above Main Idea The main idea behind this example is to handle the sess

Alejandro Estrada 104 Sep 28, 2022
React components and demo for the Tabler UI theme.

Update - June 2019: Version 2 Alpha now available on NPM: npm install [email protected] yarn add [email protected] Check out the latest progress and

Tabler 2.1k Dec 24, 2022
React components and demo for the Tabler UI theme.

React components and demo for the Tabler UI theme.

Tabler 2.1k Jan 3, 2023
Catamist, a simple Steam clone. A demo and discussion for implementing Figma design into React components

Catamist Catamist is a very simple Steam clone. The name comes from Catalyst + Catamyst + Mist (Steam synonym). A demo and discussion for implementing

M Haidar Hanif 5 Aug 5, 2022