SolidJSS
SolidJS2y ago
49 replies
ChrisThornham

Help Me Understand "use server" Security

I'm new to this topic. So please excuse me if my questions if they're obvious or don't sound well thought out. I'm simply trying to learn.

Let's assume I have an app dashboard. When a user visits that dashboard, I run a createEffect() to check their access status.

Inside that "client-side" createEffect() I call a server function getUserRecord()

Here's a simplified example to show logic.
  // Get the userId and email of logged in user
  const supabaseAuthContext = useSupabaseAuthContext()!;
  const userId = supabaseAuthContext.supabaseSession?.user.id;
  const userEmail = supabaseAuthContext.supabaseSession?.user.email;

  createEffect(async () => {
    if (userId && userEmail) {
      const userRecord = await getUserRecord(userId);      
      if (userRecord) {
        if (userRecord.has_app_access) {
          // let them access the app
        } else {
          // Navigate away
        }
      }
    }
  });


Here's the getUserRecord() function:
export async function getUserRecord(userId: string) {
  "use server";
  // Get Supabase Admin Client
  const supabaseAdmin = getSupabaseAdminClient();

  if (supabaseAdmin) {
    // Query supabase
    const { data, error } = await supabaseAdmin
      .from("users")
      .select()
      .eq("auth_user_id", userId);

    if (error) {
      console.log(error.message);
    }
    return data;
  }
}


For context, here's the getSupabaseAdminClient() function:
export function getSupabaseAdminClient() {
  "use server";

  // Get the environment variables
  const projectURL = process.env.SUPABASE_PROJECT_URL;
  const supabaseServiceRole = process.env.SUPABASE_SERVICE_ROLE;
  if (!projectURL || !supabaseServiceRole) {
    // Log error
    console.error("Unable to initialize Supabase Auth Admin Client");
    return;
  }

  return createClient(projectURL, supabaseServiceRole, {
    auth: {
      autoRefreshToken: false,
      persistSession: false,
    },
  });
}
Was this page helpful?