cocoagoat
cocoagoat

Reputation: 59

Next.js 13/14 (App Router) - Caching data fetched inside a Server Component within a DYNAMIC route

The functionality I currently have :

A Server Component where I'm fetching some data which I then pass into a Client Component. Both of those are done inside a dynamic route (app/.../[username]), and the username is also part of the POST request the data is fetched with.

So basically, user inputs username ---> dynamic route for the user is created ---> data is fetched there ---> the component loads with JSX dependent on the data.

The functionality I want :

Simply to cache the fetched data inside the user's browser for a set amount of time, so that if the same user requests the data that is relevant to them it'll be available instantly.

Why it's an issue :

According to the Next.js docs :

Whether a route is cached or not at build time depends on whether it's statically or dynamically rendered. Static routes are cached by default, whereas dynamic routes are rendered at request time, and not cached.

Link to relevant part of docs

So from what I understand, dynamic routes are never cached by default, and I couldn't find a way to make Next.js cache them. On the other side of the problem, sessionStorage isn't available in Server Components.

Is there any way to circumvent this, or are my only options basically fetching in a Client Component or back-end caching? And regardless, is the former actually fine to use in this situation? I'm very new to Next.js, this is my first project so I'm going purely based off the docs which say Server Components should be used for fetching.

Upvotes: 0

Views: 2109

Answers (1)

Yilmaz
Yilmaz

Reputation: 49729

Dynamic routes are not being cached by default. for dynamic routes generate-static-params is used:

The generateStaticParams function can be used in combination with dynamic route segments to statically generate routes at build time instead of on-demand at request time.

it is similar to getStaticPaths and getStaticProps before. if you are making update on this route, in order to see the update you have to call

import { revalidatePath } from "next/cache";

call this in function or server action

revalidatePath(`/user/${slug}`));

Upvotes: 2

Related Questions