Next.js Discord

Discord Forum

Supabase Auth caching with unstable_cache

Answered
Schneider’s Smooth-fronted Caima… posted this in #help-forum
Open in Discord
Avatar
Schneider’s Smooth-fronted CaimanOP
Hi all

I'm wondering if this approach is valid for reducing calls to supabase auth:
import { unstable_cache } from "next/cache";

import { createClient } from "@/utils/supabase/server";

export const getUser = unstable_cache(
  async () => {
    const supabase = createClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    return user;
  },
  ["user"],
  {
    revalidate: 300,
  },
);
Answered by Plague
I mean, it will achieve that yes, but it is not safe to do that, because that is a persistent cache and could lead to authentication issues where a user has logged out but still has access to your application.

React.cache is typically used for this use case to only call the user once per request no matter how many times that function is called during that single request it will be memoized.
View full answer

6 Replies

Avatar
I mean, it will achieve that yes, but it is not safe to do that, because that is a persistent cache and could lead to authentication issues where a user has logged out but still has access to your application.

React.cache is typically used for this use case to only call the user once per request no matter how many times that function is called during that single request it will be memoized.
Answer
Avatar
American Crocodile
Will react.cache work for that, even on the server side?
Avatar
Yes as long as it’s a server-side function that gets called within the component tree, (any server components or generateMetadata calls
It won’t work in Route Handlers or Server Actions, those will always fetch fresh
Avatar
Schneider’s Smooth-fronted CaimanOP
@Plague thx
Avatar
np, remember to mark as solution