<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pavel Krasnov</title>
    <description>The latest articles on DEV Community by Pavel Krasnov (@pavelkrasnov).</description>
    <link>https://dev.to/pavelkrasnov</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1594228%2F033f0116-b6f4-48f1-90b8-e4cb12988480.jpeg</url>
      <title>DEV Community: Pavel Krasnov</title>
      <link>https://dev.to/pavelkrasnov</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pavelkrasnov"/>
    <language>en</language>
    <item>
      <title>A way to speed up Next.js dynamic SSR</title>
      <dc:creator>Pavel Krasnov</dc:creator>
      <pubDate>Sun, 09 Jun 2024 13:23:12 +0000</pubDate>
      <link>https://dev.to/pavelkrasnov/a-way-to-speed-up-nextjs-dynamic-ssr-27ga</link>
      <guid>https://dev.to/pavelkrasnov/a-way-to-speed-up-nextjs-dynamic-ssr-27ga</guid>
      <description>&lt;p&gt;Let's say you have a React server component that fetches data on a server and renders a list of items:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import PokemonList from "./PokemonList";

async function fetchPokemon(id: number) {
    const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
    return response.json();
}

const pokemonIds = Array
    .from({ length: 20 })
    .map((_item, index) =&amp;gt; index + 1);

export default async function Home() {
    const pokemons = await Promise.all&amp;lt;any&amp;gt;(pokemonIds.map(item =&amp;gt; fetchPokemon(item)));

    return &amp;lt;PokemonList pokemons={pokemons} /&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You need the item list to be a client component for some reason:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import PokemonItem from "./PokemonItem";

type Props = {
    pokemons: any[];
}

export default function PokemonList({ pokemons }: Props) {
    return (
        &amp;lt;ul&amp;gt;
            {
                pokemons.map((item, index) =&amp;gt; &amp;lt;PokemonItem key={index} pokemon={item} /&amp;gt;)
            }
        &amp;lt;/ul&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As client components are also executed on a server, you will get the same code running twice on both the server and the client. But have you ever thought about what really happens when you execute the code above?&lt;/p&gt;

&lt;h2&gt;
  
  
  Next.js way to share server state with client
&lt;/h2&gt;

&lt;p&gt;When you pass props from a server component to a client in Next.js, it implicitly serializes the props and appends them to the HTML document. Then, on a client, it deserializes your props and uses them in the component they are passed to.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fktksyq05uhicgj5wjpu4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fktksyq05uhicgj5wjpu4.png" alt="Server state passed as props to a client component in the resulting HTML document" width="800" height="335"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Server state passed as props to a client component in the resulting HTML document&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  The implicit overhead
&lt;/h2&gt;

&lt;p&gt;But aren't the props serialized one time more than needed? When you query your API for JSON data using &lt;code&gt;fetch&lt;/code&gt;, you usually call the &lt;code&gt;json()&lt;/code&gt; method on the response body. When you pass the data to a client component from the server, Next.js implicitly calls &lt;code&gt;JSON.stringify()&lt;/code&gt; on them. Then isomorphic JavaScript in a client component runs twice - on a server and on a client, but though the data is already parsed on a server, Next.js has to implicitly call &lt;code&gt;JSON.parse()&lt;/code&gt; on them on a client. Let's count it: parse + stringify on a server and parse on a client. Once again, isn't the data stringified one more time than needed?&lt;/p&gt;
&lt;h2&gt;
  
  
  Fixing the issue
&lt;/h2&gt;

&lt;p&gt;The only thing we actually need to fix things is to remove the redundant serialization on a server. The response body also has other methods to read the stream. If we read it to a string by calling &lt;code&gt;text()&lt;/code&gt; instead of &lt;code&gt;json()&lt;/code&gt; and therefore not deserialize the JSON by calling &lt;code&gt;JSON.parse()&lt;/code&gt;, we will still be able to pass the response string to a client component, deserialize it there, and use it without losing anything. We would still parse the data on a server and parse it on a client, but we wouldn't stringify it on a server!&lt;/p&gt;

&lt;p&gt;This is how the "fixed" components might look:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import PokemonList from "./PokemonList";

async function fetchPokemon(id: number) {
    const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
    return response.text();
}

const pokemonIds = Array
    .from({ length: 20 })
    .map((_item, index) =&amp;gt; index + 1);

export default async function Home() {
    const pokemonsStringArray = await Promise.all&amp;lt;string&amp;gt;(pokemonIds.map(item =&amp;gt; fetchPokemon(item)));
    const pokemonsString = `[${pokemonsStringArray.join(",")}]`;

    return &amp;lt;PokemonList pokemons={pokemonsString} /&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above still queries the API for the list of items, but this time we read the response body to a string and then concatenate all the strings, making a JSON array from it. Then we pass the string to a client component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import PokemonItem from "./PokemonItem";

type Props = {
    pokemons: string;
}

export default function PokemonList({ pokemons }: Props) {
    const pokemonObjects = JSON.parse(pokemons) as any[];

    return (
        &amp;lt;ul&amp;gt;
            {
                pokemonObjects.map((item, index) =&amp;gt; &amp;lt;PokemonItem key={index} pokemon={item} /&amp;gt;)
            }
        &amp;lt;/ul&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The client component needs to explicitly do the job it would do implicitly if we passed the data as an object. This code runs on both the server and the client.&lt;/p&gt;

&lt;h2&gt;
  
  
  Note about static generation
&lt;/h2&gt;

&lt;p&gt;If you just create an app like this, Next.js will make all required requests at build time and &lt;a href="https://nextjs.org/docs/app/building-your-application/rendering/server-components#static-rendering-default"&gt;generate&lt;/a&gt; static pages. If this is enough for you, you might not need to do the thing described in this article in your app. It happens though that you need to &lt;a href="https://nextjs.org/docs/app/building-your-application/rendering/server-components#dynamic-rendering"&gt;dynamically render&lt;/a&gt; pages on every request. Dynamically rendered pages, which do their data requests on a server, are the biggest beneficiaries of the described technique. The most common scenario that will result in dynamic rendering is using Next.js &lt;a href="https://nextjs.org/docs/app/building-your-application/rendering/server-components#dynamic-functions"&gt;dynamic functions&lt;/a&gt;. For the sake of simplicity, I use the &lt;a href="https://nextjs.org/docs/app/building-your-application/rendering/server-components#segment-config-options"&gt;&lt;code&gt;force-dynamic&lt;/code&gt;&lt;/a&gt; segment config option in the example below.&lt;/p&gt;

&lt;h2&gt;
  
  
  Note about caching
&lt;/h2&gt;

&lt;p&gt;As of now (June 2024), Next.js by default &lt;a href="https://nextjs.org/docs/app/building-your-application/caching#data-cache"&gt;caches&lt;/a&gt; &lt;code&gt;fetch&lt;/code&gt; requests made on the server. During local development, the cache is stored in files in the &lt;code&gt;.next/cache/fetch-cache&lt;/code&gt; folder. But even if no actual network request is made, the response body is still deserialized using &lt;code&gt;JSON.parse()&lt;/code&gt; if you call the &lt;code&gt;json()&lt;/code&gt; method on a response body.&lt;/p&gt;

&lt;h2&gt;
  
  
  Note about data transformations
&lt;/h2&gt;

&lt;p&gt;Sometimes you don't need to just pass the data fetched on a server to a client component. You would want to apply some computations to them instead and only then send them to a client. Consider the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const pokemons = await Promise.all&amp;lt;any&amp;gt;(pokemonIds.map(item =&amp;gt; fetchPokemon(item)));

const filteredPokemons = pokemons.filter(item =&amp;gt; item.height &amp;gt; 5);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, it is necessary to parse the data on a server to process it according to your needs. You might do it in a client component instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import PokemonItem from "./PokemonItem";

type Props = {
    pokemons: string;
}

export default function PokemonList({ pokemons }: Props) {
    const pokemonObjects = JSON.parse(pokemons) as any[];
    const filteredPokemons = pokemonObjects.filter(item =&amp;gt; item.height &amp;gt; 5);

    return (
        &amp;lt;ul&amp;gt;
            {
                pokemonObjects.map((item, index) =&amp;gt; &amp;lt;PokemonItem key={index} pokemon={item} /&amp;gt;)
            }
        &amp;lt;/ul&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is totally ok, but be aware that in this case the work gets done on both server and client, which may slow down your app's client-side performance. It is a trade-off, and you should decide which part of the app has to be optimized.&lt;/p&gt;

&lt;h2&gt;
  
  
  How faster my application would be?
&lt;/h2&gt;

&lt;p&gt;Feel free to clone the &lt;a href="https://github.com/pavel-krasnov/next-json-ssr"&gt;repo&lt;/a&gt; I created as an illustration for the issue. Let's run some tests together:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run &lt;code&gt;npm run build&lt;/code&gt; to build a production version of the app;&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;npm start&lt;/code&gt; to run a local Node.js server that will serve your app;&lt;/li&gt;
&lt;li&gt;Open &lt;code&gt;http://localhost:3000/slow&lt;/code&gt; in a browser to make sure Next.js creates a filesystem data cache and the first testing request doesn't send any actual network requests;&lt;/li&gt;
&lt;li&gt;Install &lt;a href="https://github.com/hatoo/oha"&gt;oha&lt;/a&gt; - a tool we will use to send requests to the server;&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;oha http://localhost:3000/slow&lt;/code&gt;. It will send 200 requests through 50 parallel connections to the server.&lt;/li&gt;
&lt;li&gt;Stop the server and remove the &lt;code&gt;.next&lt;/code&gt; folder to make sure there is no cached data;&lt;/li&gt;
&lt;li&gt;Repeat steps 1–5, but this time use &lt;code&gt;http://localhost:3000/fast&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;My Macbook Pro M1 powered by &lt;a href="https://asahilinux.org/"&gt;Asahi Linux&lt;/a&gt; gives the following results:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;slow version:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb7pj5xuk7oox3kmntcmc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb7pj5xuk7oox3kmntcmc.png" alt="Slow page results: around 7 requests per second" width="800" height="295"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;fast version:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxb168niotj0n5et0di7s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxb168niotj0n5et0di7s.png" alt="Fast page results: around 18 requests per second" width="800" height="295"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By making one simple change, we made the app ~2.5 times faster.&lt;/p&gt;

&lt;h2&gt;
  
  
  Afterword
&lt;/h2&gt;

&lt;p&gt;This technique is used in the production version of the app I am currently working on: &lt;a href="https://tv.seznam.cz/"&gt;Czech TV schedule&lt;/a&gt;. Of course, in a complex app that does a lot of other work on the server, the effect will be more modest; in our case, it made the app around 30% faster. The need to speed up the SSR of a standalone build of this app led me to the development of a number of techniques, which I am going to share with you in this blog.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
