DEV Community

Cover image for Fun With Next.js 13 Server Components
ymc9 for ZenStack

Posted on • Updated on

Fun With Next.js 13 Server Components

Next.js 13 has landed in a somewhat confusing way. Many remarkable things have been added; however, a good part is still Beta. Nevertheless, the Beta features give us important signals on how the future of Next.js will be shaped, so there are good reasons to keep a close eye on them, even if you're going to wait to adopt them.

This article is part of a series of experiences about the Beta features. Let's play with Server Components today.


Making server components the default option is arguably the boldest change made in Next.js 13. The goal of server component is to reduce the size of JS shipped to the client by keeping component code only on the server side. I.e., the rendering happens and only happens on the server side, even if the loading of the component is triggered on the client side (via client-side routing). It's quite a big paradigm shift.

I first got to know React Server Components over a year ago from this video (watch later, it's pretty long 😄):

It feels quite "reasearch-y" by then, so I was shocked when seeing that Next.js is already betting its future on it now. Time flies and the fantastic engineers from React must have done some really great work, so I created a shiny new Next.js 13 project to play with it.

npx create-next-app@latest --experimental-app --ts --eslint next13-server-components
Enter fullscreen mode Exit fullscreen mode

Let's have some fun playing with the project. You can find the full project code here.

Server Component

The first difference noticed is that a new app folder now sits along with our old friend pages. I'll save the routing changes to another article, but what's worth mentioning for now is that every component under the app folder is, by default, a server component, meaning that it's rendered on the server side, and its code stays on the server side.

Let's create our very first server component now:

// app/server/page.tsx

export default function Server() {
    console.log('Server page rendering: this should only be printed on the server');
    return (
        <div>
            <h1>Server Page</h1>
            <p>My secret key: {process.env.MY_SECRET_ENV}</p>
        </div>
    );
}

Enter fullscreen mode Exit fullscreen mode

If you access the /server route, whether by a fresh browser load or client-side routing, you'll only see the line of log printed in your server console but never in the browser console. The environment variable value is fetched from the server side as well.

Looking at network traffic in the browser, you'll see the content of the Server component is loaded via a remote call which returns an octet stream of JSON data of the render result:

Image network traffic

{
    ...
    "childProp": {
        "current": [
            [
                "$",
                "div",
                null,
                {
                    "children": [
                        ["$", "h1", null, { "children": "Server Page" }],
                        [
                            "$",
                            "p",
                            null,
                            {
                                "children": ["My secret key: ", "abc123"]
                            }
                        ]
                    ]
                }
            ]
        ]
    }
}
Enter fullscreen mode Exit fullscreen mode

Rendering a server component is literally an API call to get serialized virtual DOM and then materialize it in the browser.

The most important thing to remember is that server components are for rendering non-interactive content, so there are no event handlers, no React hooks, and no browser-only APIs.

The most significant benefit is you can freely access any backend resource and secrets in server components. It's safer (data don't leak) and faster (code doesn't leak).

Client Component

To make a client component, you'll need to mark it so explicitly with use client:

// app/client/page.tsx

'use client';

import { useEffect } from 'react';

export default function Client() {
    console.log(
        'Client page rendering: this should only be printed on the server during ssr, and client when routing'
    );

    useEffect(() => {
        console.log('Client component rendered');
    });

    return (
        <div>
            <h1>Client Page</h1>
            {/* Uncommenting this will result in an error complaining about inconsistent
            rendering between client and server, which is very true */}
            {/* <p>My secret env: {process.env.MY_SECRET_ENV}</p> */}
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

As you may already anticipate, this gives you a similar behavior to the previous Next.js versions. When the page is first loaded, it's rendered by SSR, so you should see the first log in the server console; during client-side routing, both log messages will appear in the browser console.

Mix and Match

One of the biggest differences between server component and SSR is that SSR is at page level, while Server Component, as its name says, is at component level. This means you can mix and match server and client components in a render tree as you wish.

// A server page containing client component and nested server component

// app/mixmatch/page.tsx
import Client from './client';
import NestedServer from './nested-server';

export default function MixMatchPage() {
    console.log('MixMatchPage rendering');
    return (
        <div>
            <h1>Server Page</h1>
            <div className="box">
                <Client message="A message from server">
                    <NestedServer />
                </Client>
            </div>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode
// app/mixmatch/client.tsx
'use client';

import { useEffect } from 'react';

export default function Client({
    message,
    children,
}: {
    message: string;
    children: React.ReactNode;
}) {
    console.log('Client component rendering');

    return (
        <div>
            <h2>Client Child</h2>
            <p>Message from parent: {message}</p>
            <div className="box-red">{children}</div>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode
// app/mixmatch/nested-server.tsx

export default function NestedServer() {
    console.log('Nested server component rendering');
    return (
        <div>
            <h3>Nested Server</h3>
            <p>Nested server content</p>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

Image mixing client and server components

In a mixed scenario like this, server and client components get rendered independently, and the results are assembled by React runtime. Props passed from server components to client ones are serialized across the network (and need to be serializable).

Server Components Can Degenerate

One caution you need to take is that if a server component is directly imported into a client one, it silently degenerates into a client component.

Let's revise the previous example slightly to observe it:

// app/degenerate/page.tsx

import Client from './client';

export default function DegeneratePage() {
    console.log('Degenerated page rendering');
    return (
        <div>
            <h1>Degenerated Page</h1>
            <div className="box-blue">
                <Client message="A message from server" />
            </div>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode
// app/degenerate/client.tsx

'use client';

import NestedServer from './nested-server';

export default function Client({ message }: { message: string }) {
    console.log('Client component rendering');

    return (
        <div>
            <h2>Client Child</h2>
            <p>Message from parent: {message}</p>
            <div className="box-blue">
                <NestedServer />
            </div>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode
// app/degenerated/nested-server.tsx

export default function NestedServer() {
    console.log('Nested server component rendering');
    return (
        <div>
            <h3>Degenerated Server</h3>
            <p>Degenerated server content</p>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

If you check out the log, you'll see NestedServer has "degenerated" and is now rendered by the browser.

Is It a Better Future?

Next.js is trying everything it can to move things to the server side, exactly how people did web development two decades ago 😄. So now we're completing a full circle, but with greatly improved development experiences and end-user experiences.

For the end users, it's a clear win since computing on the server side is faster and more reliable. The result will be a much more rapid first content paint.

For developers, the paradigm shift will be mentally challenging, mixed with confusion, bugs, and anti-patterns. It will be a hell of a journey.

In the End

Thank you for your time reading to the end ❤️.

This is the first article of a series about the Beta features of Next.js 13. You can find the entire series here. If you like our posts, remember to follow us for updates at the first opportunity.


P.S. We're building ZenStack — a toolkit for building secure CRUD apps with Next.js + Typescript. Our goal is to let you save time writing boilerplate code and focus on building what matters — the user experience.

Top comments (11)

Collapse
 
silverium profile image
Soldeplata Saketos

I would say that it's completely expected that a SSComponent when called via client side it's rendered client side. This is exactly how NextJs 12 pages work.

In NextJs v12, if you land into a page, it's rendered server side. But when navigating into another page, that page is requested with a JSON request and it's closer to a client side rendered page, alleviating the weight of the "First Load JS shared by all".

So, if "/foo" weights 3kB and "/bar" weights 40kB and we have a shared first load size of 200KB:

  • Landing into "/foo" will weight 203kB, and navigating into "/bar" will download additional 40kB data.
  • Landing into "/bar" will weight 240kB, and navigating into "/foo" will download additional 3kB data.

I think that the real "paradigm shift" happening in NextJs v13 is that now, "app.js" weight could vary depending on the landing page and how many "server components" it has. Which, IMHO is a great improvement.

Collapse
 
ymc9 profile image
ymc9

Great point, and I agree. Next.js 12's getServerSideProps is already a JSON request when triggered from client-side routing. Close to server components. With 13, as you said, if a page is "pure" server-component, you get a small footprint close to SSG.

The "paradigm shift" in my head when writing this post is actually one needs to think about network boundary on a component level rather than page level. This is a new flexibility and can take time to get used to (and avoid all kinds of pitfalls).

Collapse
 
nickyru profile image
Nicky Ru

Great content!

Collapse
 
ymc9 profile image
ymc9

Thank you. Glad to know you like it 😄!

Collapse
 
arifpateldubaiprestonuk profile image
Arif Patel Dubai Preston UK

thank you For Sharing!

Collapse
 
geni94 profile image
geni94

I really liked the conclusion you put out there. It's going to be one hell of a ride for developers, for sure.

Collapse
 
mlukianovich profile image
mlukianovich

I'm new to React and Next and this is exactly what I've searched for to understand how it works. Thank you!

Collapse
 
mrdockal profile image
Jan Dočkal • Edited

Hello I'd like to add an extra bit.

For those who are wondering how to use ServerComponent inside a ClientComponent. You have to pass ServerComponent as a children instead of directly importing the ServerComponent file.

beta.nextjs.org/docs/rendering/ser...

Collapse
 
revskill10 profile image
Truong Hoang Dung

Confusing. Your code of mixing server component inside a client component is not shown here.

Collapse
 
sabbirsobhani profile image
Sabbir Sobhani

But getServerSideProps has user interactivity, and we can get both from getServerSideProps. What is the benefit of using SSC without user interactivity! Also can a SSC be mixed with Client Component?

Collapse
 
lauryfriese profile image
Info Comment hidden by post author - thread only accessible via permalink
lauryfriese

Server Components Candy Crush allows you to move component logic to the server, improving performance and reducing the amount of JavaScript sent to the client.

Some comments have been hidden by the post's author - find out more