Giter VIP home page Giter VIP logo

next-react-server-components's Introduction

Next.js App Router + React Server Components

Try the demo live here: next-rsc-hn.vercel.app.

Introduction

This is a demo app of the Hacker News website clone, which shows Next.js App Router with support for React Server Components.

Learn more.

Running Locally

  1. pnpm install
  2. pnpm dev

Go to localhost:3000.

Deploy

You can quickly deploy the demo to Vercel by clicking this link:

Deploy with Vercel

License

This demo is MIT licensed.

next-react-server-components's People

Contributors

abhi-works avatar feedthejim avatar gaearon avatar gfortaine avatar huozhi avatar khempenius avatar leerob avatar sebmarkbage avatar shuding avatar t1ger-0527 avatar timneutkens avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

next-react-server-components's Issues

Is the file locate at lib folder is server components?

I found the doc to define the server components is


All components inside the app directory are React Server Components (RSC) by default, including special files and colocated components.

How about the files on lib folder?

Missing files, but `import` statement present

The following files are referenced, but missing from the codebase:

  • ./components/comment.js from ./components/item.client.js
  • ./components/comment-form.js from ./components/item.client.js
  • ./lib/get-comments referenced from ./components/item.js

Is `next export` supported?

I tried to add next export to package.json like so "build": "yarn next build && yarn next export", but non of the pages (other then 404) is generated. Why so? Not even when I add getStaticProps to some pages, like index.js, csr.js or rsc.server.js.

Server components are broken with Next v.12.2.1

Steps to Reproduce:

  1. Clone the repository
  2. Run locally
  3. Go to /slow or /rsc
  4. Pages won`t render (infinite loading)

Fix:
After downgrading to Next v.12.1.* (currently 12.1.6) everything works as expected

Updated package.json:

{
  "scripts": {
    "dev": "yarn next dev",
    "build": "yarn next build",
    "start": "yarn next start"
  },
  "dependencies": {
    "ms": "2.1.3",
    "next": "12.1.*",
    "react": "^18.1.0",
    "react-dom": "^18.1.0"
  }
}

TransformStream is not defined

I have an error in rsc
ReferenceError: TransformStream is not defined.

and in csr
Error: Hydration failed because the initial UI does not match what was rendered on the server.

What is the problem?

Cannot set headers after they are sent to the client

Repro Steps:

  1. git clone
  2. remove yarn from package.json so i can use npm to start
  3. npm run dev
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:518:11)
    at DevServer.renderError (C:\Users\Admin\Documents\Javascript\FullStack\Next.js-Strapi-Template\next-rsc-demo\node_modules\next\dist\server\next-server.js:1631:17)
    at DevServer.run (C:\Users\Admin\Documents\Javascript\FullStack\Next.js-Strapi-Template\next-rsc-demo\node_modules\next\dist\server\dev\next-dev-server.js:431:35)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
error - TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer. Received an instance of Uint8Array
error - unhandledRejection: undefined
error - unhandledRejection: TypeError: The stream (in errored state) is not in the writable state and cannot be closed

Not working with React 18 rc.1

We are evaluating server components in our app. While attempting to get it to work, I kept getting the following error. I decided to try this simple example. Initially it works without issue, however if you update react to RC 1 (what our app is on), you get the same error we experience.

image

Routing with nextjs ?

Thanks for great demo!

One question related to routing, currently it seems impossible to read queryparams in server component.

Do you have any example/guideline for that?

Document or fix known issues with this demo

I'm starting to see this demo being used in performance comparisons in a way that implies this is the canonical RSC experience. It would be good to either solve or document (in README) concrete issues with it so that a future reader has an idea of what's correct and what's a known issue. (I've added reactjs/server-components-demo#57 to the original demo in the same spirit.)

Update

The up-to-date list of problems (likely non-exhaustive) is here: #13 (comment)


Streaming "Jank"

This demo shows each story "streaming in" individually:

bad_ux.mov

This is a rather janky user experience.

I am guessing that this demo does it to make the "streaming" aspect obvious. However, I am observing that people take away that this jankiness is what we mean by "streaming". It seems like a rather unfortunate consequence if people's takeaway becomes that apps built with Server Components have pieces randomly "popping in" — especially because the whole point of the <Suspense> model is to give you precise control over what's allowed to "pop in" individually vs what pieces must "pop in" together.

How to fix it?

If I understand correctly, there are multiple ways to fix this:

  • Remove this <Suspense> boundary so that all stories "pop in" at once. Despite delaying the display, this is a much better user experience because there's no content layout shift, and individual jumping rows aren't useful anyway.

    • I think you'll also want to replace the "top-level" spinner with null and make the body full-height so that the loading sequence before we get the stories isn't jumpy either. Ideally we'd either hold the entire page or show the shell that will be "filled in" — both of these could feel natural. A small body with a spinner in the top left corner looks weird.
    • I've tried doing that, but ran into a hydration error I couldn't fix. Is that a bug in React? For some reason, the exact place where the error happens wasn't reported in the console so I've had a hard time trying to fix this. It seems like there needs to be an investigation for:
      • Why removing this <Suspense> boundary breaks hydration
      • Why errors are not being fully reported to the console
  • Alternatively, use <SuspenseList>, replace a spinner fallback with null, and hide the tail, so that you only see stories appearing "in order". This is currently out of question because <SuspenseList> won't be in 18.0 and will come later in 18.x. It's not currently implemented on the server.

Additional server request

I am seeing an extra request to the RSC entry point from the client after the page loads:

Screenshot 2021-12-07 at 21 38 56

I wouldn't expect the initial page load to need to make any additional requests. Do we understand why it happens? Is this a bug or a known limitation of the current demo?

Thanks

I very much appreciate the work on this demo. I'm hoping we can fix and/or document the issues in it so that people are aware what's missing and don't make an impression of the overall RSC architecture or user experience based on an early demo.

Thanks!

Non-page server component cannot import client component

It seems that client components can be only directly imported from a page component.

For example, the News component located in rsc.server.js can import the Story client component just fine. If we, however, move the StoryWithData to a separate file (with the .server suffix or none i.e. a shared component), Next.js returns errors.

Here's a diff off a branch from my fork that shows this issue:
main...zaiste:non-page-server-comp-cannot-import-client-comp

Webpack error when trying to use a component that statically imports an image

First off I don't know if this is the right place to open this issue, apologies if it isn't.

I am trying out React Server Components with Next.js v12.2.3. This is the workflow I am trying to do:

Directory structure:
image

// pages\blog\[slug].server.tsx
import type { GetStaticPropsContext } from "next";
import Image from "next/image";

import * as POST_1 from "../../content/post-1/index.server";
import * as POST_2 from "../../content/post-2/index.server";

const slugToModule = {
  "post-1": POST_1,
  "post-2": POST_2,
};

type Props = {
  slug: string;
};

export default function BlogPostPage({ slug }: Props) {
  // @ts-expect-error
  const { default: MDXContent, meta } = slugToModule[slug];
  return (
    <main>
      <h1>{meta.title}</h1>
      {meta.coverImage && <Image src={meta.coverImage.src} alt={meta.coverImage.alt} />}
      <MDXContent />
    </main>
  );
}

export async function getStaticPaths() {
  const slugs = Object.keys(slugToModule);

  return {
    paths: slugs.map((slug) => ({
      params: { slug },
    })),
    fallback: false,
  };
}

type Params = {
  slug: string;
};

export async function getStaticProps({ params }: GetStaticPropsContext<Params>) {
  return {
    props: { slug: params!.slug },
  };
}
// content\post-1\index.server.tsx
import coverImage from "./cover-image.jpg";

export const meta = {
  title: "Post 1",
  coverImage: {
    src: coverImage,
    alt: "Alt description",
  },
};

export default function Content() {
  return (
    <main>
      <p>This is post 1 content.</p>
    </main>
  );
}

I am getting the following error:

❯ npm run build  

> [email protected] build
> next build

warn  - You have enabled experimental features (runtime, serverComponents) in next.config.js.
warn  - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use at your own risk.

info  - SWC minify release candidate enabled. https://nextjs.link/swcmin
info  - Linting and checking validity of types  
warn  - You are using the experimental Node.js Runtime with `experimental.runtime`.warn  - You have experimental React Server Components enabled. Continue at your own risk.
info  - Creating an optimized production build  
Failed to compile.

C:Usersmiolivercodepersonal     est-rsc-next-imagecontentpost-1cover-image.jpg     
Module build failed: UnhandledSchemeError: Reading from "C:Usersmiolivercodepersonal       est-rsc-next-imagecontentpost-1cover-image.jpg" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "c:" URIs.
    at C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:57269:25
    at Hook.eval [as callAsync] (eval at create (C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:23385:10), <anonymous>:6:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:23187:14)     
    at Object.processResource (C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:57266:8)
    at processResource (C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:20797:11)
    at iteratePitchingLoaders (C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:20748:10)
    at runLoaders (C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:20974:2)
    at NormalModule._doBuild (C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:57256:3)
    at NormalModule.build (C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:57400:15)
    at C:\Users\mioliver\code\personal\test-rsc-next-image\node_modules\next\dist\compiled\webpack\bundle5.js:31406:12

Import trace for requested module:
./node_modules/next/dist/build/webpack/loaders/next-flight-client-entry-loader.js?modules=next%2Fimage&modules=C%3A%5CUsers%5Cmioliver%5Ccode%5Cpersonal%5Ctest-rsc-next-image%5Ccontent%5Cpost-1%5Ccover-image.jpg&runtime=nodejs&ssr=false&name=pages%2Fblog%2F%5Bslug%5D&server=true!


> Build failed because of webpack errors

If I remove the static image import/export from content\post-1\index.server.tsx tha it builds fine!

Breaks browser button behavior and unnecessarily re-renders page

Reproduction:

  1. Go to https://next-rsc-demo.vercel.sh/csr or https://next-rsc-demo.vercel.sh/rsc
  2. Click into a post's comments
  3. See skeleton and wait for "loading comments"
  4. Toggle close one of the comment threads.
  5. Click browser back button, to go back to main page.
  6. Click browser forward button.
  7. Problem: Now you have to experience step 3. again.
  8. Problem: The comment thread you previously toggled will now be untoggled. Due to the re-rendering.

Expectation:

Clicking browser Forward button in step 6. should simply take you to the page you previously just saw. Also, the state of anything you toggled on that page should be the same as how you put it when you clicked the browser Back button.

Server dependency is being included in the frontend bundle

Hey all, first of all thank you for the interesting demo.

It seems that the demo is quite not fulfilling one of the main purposes of RSC, which is to keep server dependency in the server.

Example:

// ./components/Time.server.js

import moment from "moment";

const Time = () => {
  return <p>{moment().format("DD/MM/yyyy H:mm")}</p>;
};

export default Time;
// ./pages/index.js 

import { Suspense } from "react";
import Time from "../components/Time.server";

export default function Index() {
  return (
    <Suspense fallback={"Loading..."}>
      <Time />
    </Suspense>
  );
}

The moment dependency is being included into the client bundle, checked the chunks into .next/static folder and also with @next/bundle-analyzer:

image

What is the Nav component doing?

Hi everyone,

Thanks for sharing this demo!

I was looking at the source of Nav component:

export default function Nav() {
  ;<ul className="nav-ul">
    <Item href="/newest">new</Item>
    ...

    <style jsx>{`
       ...
    `}</style>
  </ul>
}

Why is this component returning undefined? What does it do if nothing is being returned?
How does this have an effect on DOM, state, styles, or anything else?
Is this a common pattern? Where can I read more about this? I'm intrigued :)

Why is a bunch of js files loaded?

Hi, sorry if I'm misunderstanding, or maybe it's because Server Components are still alpha, but I was under the impression that this demo would load zero javascript.

If I look in the browser devtools network tab on https://next-news-rsc.vercel.sh/csr for example I'm seeing it loads a bunch of js files like https://next-news-rsc.vercel.sh/_next/static/chunks/313-ac2dffa02b6a4c2a.js.

Is this because the functionality is not out of alpha, or am I understanding wrong? Would love to use this.

Handling error in data fetching

Currently if there're errors of data fetching on server side, it will just hang with suspense fallbacks instead of providing a useful error message. Need to provide a better way of helping notice errors of data fetching, easiler espically in dev mode

trailing slash does not seem to work with RSC on

Having trailingSlash: true does not seem to work if you turn on serverComponents. I'm not sure if this is the right place to raise it up or on the actual project considering it's still on alpha.

RSC with delay example broken

Steps to Reproduce:

  1. Clone the repository
  2. Run locally
  3. Go to /slow
  4. It will show this error: Error: storyIds.slice is not a function

Fix:

function NewsWithData() {
  const { data: storyIds } = useData('top', () => fetchData('topstories', 500))
  return (
    <>
      {storyIds
        ? storyIds.slice(0, 30).map((id) => {
            return (
              <Suspense key={id} fallback={<Spinner />}>
                <StoryWithData id={id} />
              </Suspense>
            )
          })
        : null}
    </>
  )
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.