I can use the service role in a NextJS Route Handler to bypass RLS. This code works:
import { createClient } from "@supabase/supabase-js";
export async function POST(request: Request) {
const adminClient = createClientJS(projectUrl, serviceRole);
const res = await adminClient
.from("profiles")
.update({ credits: 123 })
.eq("id", userId)
.select();
console.dir(res, { depth: null });
If I follow the docs for NextJS (https://supabase.com/docs/guides/auth/server-side/creating-a-client?environment=route-handler)
It works when using the anon key but not the service role key:
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { cookies } from 'next/headers'
export async function POST(request: Request) {
const cookieStore = cookies();
const adminClient2 = createServerClient(projectUrl, serviceRole, {
cookies: {
get(name: string) {
return cookieStore.get(name)?.value;
},
set(name: string, value: string, options: CookieOptions) {
cookieStore.set({ name, value, ...options });
},
remove(name: string, options: CookieOptions) {
cookieStore.set({ name, value: "", ...options });
},
},
});
const res = await adminClient2
.from("profiles")
.update({ credits: 123 })
.eq("id", userId)
.select();
console.dir(res, { depth: null });
The console.dir
returns a status of 200 and no errors but the database isn't updated.
Is this a bug or does supabase-js not support using the service role?
Just use the createClient
imported from @supabase/supabase-js
when using the service role key as all the other createClient
methods will override the service role key with whatever auth token there is in the cookie.
import { createClient } from "@supabase/supabase-js";