next-react-server-components icon indicating copy to clipboard operation
next-react-server-components copied to clipboard

Routing with nextjs ?

Open revskill10 opened this issue 2 years ago • 5 comments

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?

revskill10 avatar Oct 30 '21 18:10 revskill10

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.

shuding avatar Oct 31 '21 01:10 shuding

@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 ?

revskill10 avatar Oct 31 '21 08:10 revskill10

@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...

shuding avatar Oct 31 '21 08:10 shuding

@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 ?

revskill10 avatar Oct 31 '21 09:10 revskill10

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?

carlosagsmendes avatar Nov 07 '21 22:11 carlosagsmendes

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

leerob avatar Nov 13 '22 17:11 leerob