Next.js Discord

Discord Forum

Unable to cache authenticated requests

Unanswered
Ichneumonid wasp posted this in #help-forum
Open in Discord
Ichneumonid waspOP
Hello, I am using Nextjs 16 with cached components and Supabase for my auth. In my current setup I enforce authentication at 4 layers. 1) Proxy file is the first place where I redirect, 2) Protected routes enforce auth themselves, 3) Server Actions are all authed and 4) my DAL functions all require auth.

I am trying to cache my DAL functions because I feel re-fetching profile data over and over every time the user navigates to or refreshers the profile page is not the proper way of handling it. However for some reason nothing gets cached. I am using cache:private to make sure each request is cached per session.

Is this the correct way to go about this? How would I cache user data so I dont have to refetch everything on navigation? Here is an example of one my DAL methods:

const getSubscriptionByUserIdCached = async (user_id: string, fieldString: string, authenticated: boolean) => {
    'use cache: private';
    cacheLife('minutes');
    cacheTag(`user-subscription-${user_id}`);

    if (!authenticated) throw new UnauthorizedError("User not authorized");
    const supabase = await createClient();

    const { data, error } = await supabase
        .from("subscription")
        .select(fieldString as "*")
        .eq("user_id", user_id)
        .maybeSingle();

    return data;
};

export class SubscriptionDAL {
    private constructor(private readonly authenticated: boolean = false) { }

    static async create(): Promise<SubscriptionDAL> {
        await requireAuth();
        return new SubscriptionDAL(true);
    }

    getSubscriptionByUserId = async (user_id: string, fields?: string[]) => {
        const fieldString = fields?.length ? fields.join(",") : "*";
        return getSubscriptionByUserIdCached(user_id, fieldString, this.authenticated);
    };

EDIT: supabase's createClient() uses the cookie API to ready the user and create an Authenticated client. That means that on any place I check auth the route becomes dynamic (??)

0 Replies