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:
25
apps/web/lib/server/require-user-in-server-component.ts
Normal file
25
apps/web/lib/server/require-user-in-server-component.ts
Normal 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;
|
||||
});
|
||||
Reference in New Issue
Block a user