In October 2022, React Server Components were introduced and the Next.js Team worked hard on incorporating it into Next.js over the next several months.

With “app router” going stable now, RSC is officially supported in Next.js here’s what you need to know!

What is a Server Component?

Previously, Next.js rendered React on the server as html and hydrated the sent html with event listeners & interactivity in the browser.

Data fetching on individual pages was done through various framework-specific functions like getServerSideProps, getStaticProps, etc. and via API endpoints present in the pages/api directory. With the new “app router” as they like to call it, these special functions are obsolete in the favour of RSC.

Here’s an example of a Next.js page present at the “/” path

Untitled

Untitled

Notice that this is an async function where we’re awaiting prisma db call for fetching posts.

“But, wait… won’t this run on a browser too?”

This is different from the way it used to run on server AND browser, the special thing about a Server Component is that they run ONLY on the server and never on the browser.

When client requests for the page, the server waits for the awaited promise findMany() to finish, renders the page and sends the resulting HTML to the client.

Next.js will consider all the components as a Server Component by default, so if we try adding any interactive features like a state variable or a useEffect or try calling the window object, It errors out.

Untitled

Let’s follow the above error, it requires us to add a line "use client"; in the component

Untitled

Hmm… the linter warns us for using the an async function in a client component, so this means, Next.js is now taking this as a client component, let’s look at the result in the browser…

Untitled

Quick Note: Prisma can’t run in a browser environment, it needs Node.js runtime for normal functioning.

Now, it is talking about the db.ts where we are initializing a Prisma Client and the fact that this error is occuring in the browser, it must mean that the component is now being run in the browser too during the hydration phase.