In my case, I only want authenticated users to perform a SELECT query on my database, so I set up my RLS Policy for this scenario. This is where I am hitting an issue. With RLS enabled, I need to let the server know that I am authenticated when making a request, but it hits unauthorized all the time.
My RLS Policy:
alter policy "Read all locations"
on "public"."sampling_location"
to public
using (
(auth.role() = 'authenticated'::text)
);
This is how my frontend makes a request on my API endpoint:
const response = await fetch('/api/locations');
This is my code block on making a fetch request on Supabase:
export async function GET(request: NextRequest) {
const supabase = createSupabaseServerClient();
// Check if user is authenticated
const {
data: { user },
error
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const { searchParams } = new URL(request.url);
const region = searchParams.get('region');
let query = supabase
.from('sampling_location')
.select('*')
.order('created_at', { ascending: false });
if (region) {
query = query.ilike('region', `%${region}%`);
}
const { data, error} = await query;
if (error) throw error;
return NextResponse.json(data.map(normalizeLocation), { status: 200 });
} catch (error) {
return NextResponse.json({ error: getErrorMessage(error) }, { status: 500 });
}
}