vercel / next-react-server-components

Demo repository for Next.js + React Server Components
https://next-rsc-hn.vercel.app
MIT License
979 stars 158 forks source link

Routing with nextjs ? #6

Closed revskill10 closed 1 year ago

revskill10 commented 2 years ago

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?

shuding commented 2 years ago

Yeah, currently React Context isn’t implemented in RSC so we can’t use useRouter in server components. As a temporary workaround, router is passed to the page as a prop (same as the withRouter behavior).

But this is just a temporary workaround and RSC is still an experimental thing, this will change in future updates.

revskill10 commented 2 years ago

@shuding I tried to use withRouter for main component but got error

Error: This Hook is not supported in Server Components.

Do you have any guideline for it ?

shuding commented 2 years ago

@revskill10 It's already there, you don't need to wrap it with withRouter:

export default function Page({ router }) {
  ...
}

Also keep in mind that this router object only has query, route and asPath fields...

revskill10 commented 2 years ago

@shuding I tried with this, one concern is, i have to check if router is defined first, else return null at first render.

Here's my demo application:

https://github.com/revskill10/rsc-demo/blob/main/pages/demo.server.tsx

It runs fine in dev with vercel dev but failed to deploy to vercel (build succeeded, but error in runtime)

/demo
16:33:56:83
EvalError: Code generation from strings disallowed for this context
at Function (<anonymous>)
at Module../pages/demo.server.tsx
at r
at Module../node_modules/next/dist/build/webpack/loaders/next-middleware-ssr-loader/index.js?page=%2Fdemo&absolutePagePath=private-next-pages%2Fdemo.server.tsx&isServerComponent=true&buildId=ty_jofvrD0MAXupxHwHlM&basePath=&assetPrefix=!
at r
at n
at Object.<anonymous>

Could you check why it failed in production then ?

carlosagsmendes commented 2 years ago

Also keep in mind that this router object only has query, route and asPath fields...

Thanks for the clarification. But the plans are to get back access to the context in the page, right?

leerob commented 1 year ago

This is now supported: https://github.com/vercel/next-react-server-components/blob/main/app/item/page.js#L9-L12

https://beta.nextjs.org/docs/api-reference/file-conventions/page