Add more efficient authentication check function to server components.

Added request logging to Next.js config.

This commit introduces a new function 'requireUserInServerComponent' which checks for user authentication and is used in multiple server components. The aim is to enhance efficiency by caching the function so that data is only fetched once per request, preventing unnecessary database hits. Existing components were modified accordingly to incorporate this new method.
This commit is contained in:
giancarlo
2024-06-04 11:54:04 +07:00
parent 16c0f07e59
commit 3261f2b582
7 changed files with 44 additions and 50 deletions

View File

@@ -0,0 +1,25 @@
import 'server-only';
import { cache } from 'react';
import { redirect } from 'next/navigation';
import { requireUser } from '@kit/supabase/require-user';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
/**
* @name requireUserInServerComponent
* @description Require the user to be authenticated in a server component.
* We reuse this function in multiple server components - it is cached so that the data is only fetched once per request.
* Use this instead of `requireUser` in server components, so you don't need to hit the database multiple times in a single request.
*/
export const requireUserInServerComponent = cache(async () => {
const client = getSupabaseServerComponentClient();
const result = await requireUser(client);
if (result.error) {
redirect(result.redirectTo);
}
return result.data;
});