Whenever I ask a question like: "When the cache will resets?" You always answer my question in seconds. Thank you for this very important and easy solution.
Btw for fetch api calls, nextjs natively memoizes the results of the fetch request. So if you make the same fetch request in multiple components in the react tree, you don't need to use the new cache requests. This only applies to the native fetch api. If you are using libraries like axios to fetch or database ORMs then cache is the move like Cody shows.
I think it's also important to mention that this is already built in for regular fetches in React. React essentially automatically extends the fetch API and will return the cached fetch requests on a per request basis. This becomes especially important if you are fetching from the database (like you are in this function), because that will not get cached automatically.
How people missunderstand such things. React has nothing to do with fetch. Its behaviour that nextjs introduced and made it default which is sooo wrong. Fortunately they remove it as a default and instead it will be opt in in nextjs 15
@@Vantivify You're the one unfortunately misunderstanding. React ALSO extends the fetch API. That is why in the video he is importing from React and not Nextjs. This video is about request memoization which is a React caching layer. You are talking about the nextjs data cache layer, that is what is being turned off in nextjs 15. Look up request memoization if you don't believe me.
Really useful stuff. Especially when you host your app on a "pay per-request" platform you do not want to have it make 7 requests on a page refresh per user.
Question: Aren't those children components client components? How are you even using the validateRequests() function inside them? What I do when using lucia is have a parent server component that checks if the user exists in validateRequests() and if they do I pass it as a prop to the children client components for rendering reasons (log out button, displaying someone's name etc) and if it doesn't exist I simply redirect the user to a login page. I believe that way the function also gets called only once.
Yeah I only run getCurrentUser inside server components and often I’ll show different client components if the user is authenticated or not. Sometimes I’ll pass in the user info into the client components, but I often find it better to just try to conditionally show things in the RSC
@@nasko235679 I believe it's running 6-7 times because we're looking at the outputted console.log statement from a function, whereas by default Server Components will usually look to memoize duplicate fetch requests instead (i.e. if the same fetch request is called multiple times from different components). So therefore, if your function had to do a lot of heavy calculations immediately after receiving that fetch data, then the cache idea would be a perfect opportunity to use it, to help ensure those calculations are only run once.
Thank you for that Cody. Really helpful. If I understand correctly, pretty new to nextjs deving, since it's caching the info, could it replace a React Context since you don't really need to store the data but just get the cached version of the call ?
Thank you for sharing! This shows how important it is to check the # of renders/function calls in react. Curious to know if useContext hook can also work (wrapping the overall root in context provider and then using it in components) or no?
but, how does internally cache handles the weakmap to be clear when the request is over? that is the question I wonder how react server components handles that 🤔
might be a stupid question but how does this work with server components? After working on a few projects I noticed that the response is usually cached on build time in production and not on refresh. Does this cache function override the default nextjs behavior to revalidate on build time and instead revalidates on user request, for instance a Ctrl + R?
Currently working aswell on a SaaS starter with some cool functionalities implemented. Strongly feel you when you tell that you'll never finish that boilerplate 😂 and nice one!!
forgive my next.js react ignorance but: for how long does the cache holds ? from what I understood the cache holds until a full page relaod happens ? in this case why not just call the function once and put it in a global frontend state store ?
Idk how to answer this honestly. The cache is per request. Sometimes you need to verify values on each request on your backend. Sometimes different RSC in your tree might need the same data during your SSR, so you’d cache it server side
This is a different level of cache, this cache (request memoization) get evicted after the request ends. NextJS has 4 levels of caching, I know, extra confusing. You are talking about the Data cache.
@@hello19286I understand but I'm asking about this specific use case since we know probably the user data won't change unless maybe u change your profile or do certain actions then you refresh the user data by fetching the user again. Isn't this a common practice among next.js devs to have a front end state store for such use cases ? Fetch once, share anywhere and refresh on need.
how about moving things so that doesn't need to be send over rsc to client component like the button leave so if there is issue (or security issue) with the cache fct that react core team is giving us it won't affect us (I think rsc are good for small peoject but for larger project I prefer having front and backend separated so it easiest to keep track of bug and to separate concern)
So I 'm using middleware with next-auth and jwt strategy to avoid calling db because you can't unless db is serveless. i guess with react cache i can avoid middleware and use db sessions right?
Yes, it’s hard to answer this question. You cant connect to a database from your middleware because it requires serverless compatible libraries. Many database drivers are not serverless friendly, such as a postgres driver. This means that you either need to expose an api endpoint on your app and do a fetch request from your middleware to your api (which is slow and defeats the purpose of middleware running on edge), or you need to find a driver that will work (or find a way to expose your database over https publically which I’d say is a security concern). My personal opinion is to not use middleware because of added complexity and to just verify sessions on your RSC directly.
I've always put that kind of stuff in global store and only do the request if the information is missing (essentially the first time the app loads). Is this not a good practice?
I mean, you should really be checking and validating the users, tokens or sessions every single request. For example, if someone invokes your server action, you need to make sure that the Paul request has a valid non-expired session so you can’t really trust that any other way, other than the look it up every time.
I learned something new, when the video started, I thought you were going to use react context. Do people still use context is apps now days or is it not recommended for using data in our app
Context is often still needed for various things. I guess it depends on what you need it for. Often you’ll fetch the initial value in your RSC and populate the context value using it so the client component can use it when it hydrates
This is cache method is not cacheing at all. It does request deduplication acctualy. If multiple compoments call this func at same time, it Will be executed only once and its return value Will be forwarded to every place where it was called. But yea, nothing is "cached" (saved for later)
I use node js as backend. I get the similar multiple calls to verify jwt when a page loads. (So, I did the verify jwt in that middleware itself, want to know if it's a good practice .) I tried the cache in the middleware.ts const verifyToken = cache( async (tokenName: string, req: NextRequest): Promise => { ///logic }); It's throwing this error TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_2__.cache) is not a function
Verifying the jwt in the middleware is also fine. You shouldn’t need to call cache in the middleware. If the token is invalid just redirect the user to another page. I think you’d still need to call a method to get the user session inside your RSC.
Said hook, but meant function. Don’t kill me
Whenever I ask a question like: "When the cache will resets?" You always answer my question in seconds. Thank you for this very important and easy solution.
rsc in the mud. react query ftw
Good Cody: Uses Bearded Blue theme
Evil Cody: Doesnt use Bearded Blue theme
The maintainer of bearded theme is cookn up my own webdevcody theme with my brand colors 🤣 I’m going to suss it out to see if people hate it or not
@@WebDevCody that's great lol
Btw for fetch api calls, nextjs natively memoizes the results of the fetch request. So if you make the same fetch request in multiple components in the react tree, you don't need to use the new cache requests. This only applies to the native fetch api. If you are using libraries like axios to fetch or database ORMs then cache is the move like Cody shows.
From nextjs 15 it wont be the default behaviour.
Would that be a security issue?
I think it's also important to mention that this is already built in for regular fetches in React. React essentially automatically extends the fetch API and will return the cached fetch requests on a per request basis. This becomes especially important if you are fetching from the database (like you are in this function), because that will not get cached automatically.
Often you can’t use fetch to get data from a database. You usually use a database driver.
How people missunderstand such things. React has nothing to do with fetch. Its behaviour that nextjs introduced and made it default which is sooo wrong. Fortunately they remove it as a default and instead it will be opt in in nextjs 15
@@Vantivify You're the one unfortunately misunderstanding. React ALSO extends the fetch API. That is why in the video he is importing from React and not Nextjs. This video is about request memoization which is a React caching layer. You are talking about the nextjs data cache layer, that is what is being turned off in nextjs 15.
Look up request memoization if you don't believe me.
Really useful stuff. Especially when you host your app on a "pay per-request" platform you do not want to have it make 7 requests on a page refresh per user.
straight up "I just know nextjs thumbnail" right here
Question: Aren't those children components client components? How are you even using the validateRequests() function inside them? What I do when using lucia is have a parent server component that checks if the user exists in validateRequests() and if they do I pass it as a prop to the children client components for rendering reasons (log out button, displaying someone's name etc) and if it doesn't exist I simply redirect the user to a login page. I believe that way the function also gets called only once.
Yeah I only run getCurrentUser inside server components and often I’ll show different client components if the user is authenticated or not. Sometimes I’ll pass in the user info into the client components, but I often find it better to just try to conditionally show things in the RSC
@@WebDevCody If you're doing that why is the request running 6-7 times? Isn't it supposed to run on the initial request of the server component only?
@@nasko235679 I believe it's running 6-7 times because we're looking at the outputted console.log statement from a function, whereas by default Server Components will usually look to memoize duplicate fetch requests instead (i.e. if the same fetch request is called multiple times from different components). So therefore, if your function had to do a lot of heavy calculations immediately after receiving that fetch data, then the cache idea would be a perfect opportunity to use it, to help ensure those calculations are only run once.
What keyboard do you use? It sounds amazing
Klack.app
Cody did a video on the app th-cam.com/video/AJDSZcv27JI/w-d-xo.html
Thank you for that Cody. Really helpful. If I understand correctly, pretty new to nextjs deving, since it's caching the info, could it replace a React Context since you don't really need to store the data but just get the cached version of the call ?
Cache is specifically for your RSC, context is for your client components. It’s different imo
Thanks man! Learned something new
Awesome video. But do next-auth/clerk cache the session request for me or do I need to do it manually?
Thank you for sharing! This shows how important it is to check the # of renders/function calls in react.
Curious to know if useContext hook can also work (wrapping the overall root in context provider and then using it in components) or no?
Curious as well
See this what I do then recall through middleware for certain pages I’m not sure if it’s right or wrong but I do it 😅
wow this one was super helpful. thanks!
but, how does internally cache handles the weakmap to be clear when the request is over? that is the question I wonder how react server components handles that 🤔
might be a stupid question but how does this work with server components? After working on a few projects I noticed that the response is usually cached on build time in production and not on refresh. Does this cache function override the default nextjs behavior to revalidate on build time and instead revalidates on user request, for instance a Ctrl + R?
If you’re on a page that uses a cookie the page will always be dynamic
Great content as always. Love this short but informative videos ❤
Does anybody know which keyboard is Cody using? it sounds awesome
he should be using the macbook keyboard with a software that adds the sound of key press on the recording. he has a video showing it
Currently working aswell on a SaaS starter with some cool functionalities implemented. Strongly feel you when you tell that you'll never finish that boilerplate 😂
and nice one!!
What theme you use in VS code ?
Hey Cody, what keyboard do you have? It sounds amazing
Klack app
may be create a hook with Context API, that will use same instance
Thank you so much Cody,
Please which extension are you using for your error to show directly on the editot?
Error lens
whats the diffrence between unstable_cache and cache?
Thank you so much
What is this theme name ? i loved
Web dev Cody theme
@@WebDevCody Can i wish theme link 😂
how do you revalidate the cached data if you update for example the avatar of your profile, without refreshing the entire page
RevalidatePath or revalidateTag but those are unrelated to what I just discussed
There is always something to learn from your videos. Thank you !
forgive my next.js react ignorance but:
for how long does the cache holds ?
from what I understood the cache holds until a full page relaod happens ?
in this case why not just call the function once and put it in a global frontend state store ?
Idk how to answer this honestly. The cache is per request. Sometimes you need to verify values on each request on your backend. Sometimes different RSC in your tree might need the same data during your SSR, so you’d cache it server side
This is a different level of cache, this cache (request memoization) get evicted after the request ends. NextJS has 4 levels of caching, I know, extra confusing. You are talking about the Data cache.
@@hello19286I understand but I'm asking about this specific use case since we know probably the user data won't change unless maybe u change your profile or do certain actions then you refresh the user data by fetching the user again.
Isn't this a common practice among next.js devs to have a front end state store for such use cases ?
Fetch once, share anywhere and refresh on need.
Which theme? Feels easy to look at.
Bearded theme feat web dev Cody. It’s not out yet
@@WebDevCodyohh, nice one.
how about moving things so that doesn't need to be send over rsc to client component like the button leave so if there is issue (or security issue) with the cache fct that react core team is giving us it won't affect us (I think rsc are good for small peoject but for larger project I prefer having front and backend separated so it easiest to keep track of bug and to separate concern)
All my buttons and forms are always client components. I’m not sure I understand what you’re asking
@@WebDevCody if it's client side just make a context and all your client component check from the context
So I 'm using middleware with next-auth and jwt strategy to avoid calling db because you can't unless db is serveless. i guess with react cache i can avoid middleware and use db sessions right?
Yes, it’s hard to answer this question. You cant connect to a database from your middleware because it requires serverless compatible libraries. Many database drivers are not serverless friendly, such as a postgres driver. This means that you either need to expose an api endpoint on your app and do a fetch request from your middleware to your api (which is slow and defeats the purpose of middleware running on edge), or you need to find a driver that will work (or find a way to expose your database over https publically which I’d say is a security concern). My personal opinion is to not use middleware because of added complexity and to just verify sessions on your RSC directly.
I've always put that kind of stuff in global store and only do the request if the information is missing (essentially the first time the app loads). Is this not a good practice?
I mean, you should really be checking and validating the users, tokens or sessions every single request. For example, if someone invokes your server action, you need to make sure that the Paul request has a valid non-expired session so you can’t really trust that any other way, other than the look it up every time.
Is this something that needs to be done with Clerk as well - or is it just next auth Lucia thing?
No clue, you’d need to check their docs or look to see if they call cache somewhere
So cache is like useMemo but on the server?
Yeah
I learned something new, when the video started, I thought you were going to use react context. Do people still use context is apps now days or is it not recommended for using data in our app
Context is often still needed for various things. I guess it depends on what you need it for. Often you’ll fetch the initial value in your RSC and populate the context value using it so the client component can use it when it hydrates
@@WebDevCody makes sense, i see RSC has replaced a lot of the old fetch paradigms
what about next auth where can i add react cache to make it efficient
i am also using convex for backend
Learned something new today. Day improved
I personally like to fetch the user in the root layout and pass it to React Query as initialData in a context.
Been going through exactly this with my next.js supabase app
gengar!!
can you not just call getcurrentuser from root and then pass the value with the context api?
You can’t access context values in RSC, but yes you could pass it down as props if you want
Lmao that joke at the start
Without stained blue it feels weird :D
i don't think I was ever first! Learned about this recently on Josh's Comeau course, definitely a good one to keep in mind
kind of hard to imagine why this problem would exist in the first place
Wouldn't this be a client-only concern instead of something on the server?
Not sure what you mean
Good job love!!! First!!
You’ll get your reward later tonight
@@WebDevCody woah
i was not expecting this when trying to learn react
@@WebDevCodyAwww! Cuddles and a cup of cocoa later tonight.
@@Innesb 🤣
🐐
real chads use trpc + react query
Someone got a clickety-clack keyboard, didn’t they?
This would be 100% easier to watch if there wasn’t loud af typing
Sorry, many people like it
This is cache method is not cacheing at all.
It does request deduplication acctualy.
If multiple compoments call this func at same time, it Will be executed only once and its return value Will be forwarded to every place where it was called.
But yea, nothing is "cached" (saved for later)
Take that up with the react team 😉
Next.js sucks! Use remix!!!
It will implement RSC very soon so it doesn't change anything to be honest
I use node js as backend.
I get the similar multiple calls to verify jwt when a page loads. (So, I did the verify jwt in that middleware itself, want to know if it's a good practice .)
I tried the cache in the middleware.ts
const verifyToken = cache(
async (tokenName: string, req: NextRequest): Promise => {
///logic
});
It's throwing this error
TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_2__.cache) is not a function
Verifying the jwt in the middleware is also fine. You shouldn’t need to call cache in the middleware. If the token is invalid just redirect the user to another page. I think you’d still need to call a method to get the user session inside your RSC.