How to do Proper SSR and Data Fetching in Next.js 14 App Router? – Next.js

by
Alexei Petrov
app-router next.js next.js13 reactjs server-side-rendering

Quick Fix: Use the async function keyword to fetch data on the server side and store it in a variable. Pass this variable to the client component, which is rendered using the "use client" directive. This approach ensures server-side rendering with data hydration on the client.

The Solutions:

\n

Solution 1: Handle DataFetching on SSR

\n

Implement a universal helper function for fetching data that can be used across all pages.

Use getServerSideProps or getInitialProps to fetch data on the server side.

Store the fetched data on the component’s props object.

The function should accept the necessary parameters for making the fetch request, such as the URL, method, headers, and body.
The function should return the response of the fetch request.

\n

Solution 2: Use SWR for Data Fetching

\n

UseSWR library to fetch data on the client side.

Wrap the data fetching logic inside a custom hook.

Utilize the hook within components to access and display the fetched data.

SWR provides built-in support for caching and revalidation, making it a convenient choice for data fetching in Next.js applications.

Q&A

Can data fetching still maintain SSR characteristics with "use client" in the component?

No, data fetching inside "use client" is client-side and won’t have SSR characteristics.

Is it possible to fetch data as SSR and store it in a hook?

No, it’s not possible to pass SSR-fetched data to the client through hooks.

What happens if I call data fetching inside a hook?

UI will render on the server without data and hydrate on the client.

Video Explanation:

The following video, titled "Server-side data fetching in Next.js 12 vs. 13 - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Next.js introduced the `app/ directory (beta), which allows you to fetch data directly in server components. Watch Sam Selikoff show a demo ...