createClient() creates issues with Next 16 Cached Components
Hi, I'm upgrading to NextJS 16. I've just watched John's new Youtube video. He says that if you are making public calls to the database and auth cookies are not necessary, you can use a "anon" version of createClient using auth options. This allows a cookie-less supabase instance to be created.
HOWEVER, NextJS doesn't seem to like this (see error message below) due to part of the code calling "Math.Random()" and it needing deterministic code.
Any ideas of what to do about this? The only way I've found to solve this so far is to cache the component that uses the client. But I don't really want it to be a cached component (I realise that in that case I could just use the cookie-d version of the supabase client in this case, but that doesn't feel like a proper solution and would add to code complexity). Maybe I'm thinking about this wrong ?
Thanks!
--- Next error message ---
Route "/directory" used
Math.random() before accessing either uncached data (e.g. fetch()) or Request data (e.g. cookies(), headers(), connection(), and searchParams). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random
node_modules/.pnpm/@supabase+auth-js@2.76.1/node_modules/@supabase/auth-js/src/lib/helpers.ts (14:21) @ <anonymous>
12 | export function uuid() {
13 | return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
> 14 | const r = (Math.random() * 16) | 0,
| ^
15 | v = c == 'x' ? r : (r & 0x3) | 0x8
16 | return v.toString(16)
17 | })2 Replies
Can you share a snippet of your code example where this is happening?
Sure thing:
getAllPlacesCategories:
export const getAllPlacesCategories = cache(async () => {
const supabase = createAnonClient();
const response = await supabase.from('places_categories').select('*');
return response;
});
createAnonClient :
import { Database } from '@/types_db';
import { createClient as createSupabaseClient } from '@supabase/supabase-js';
export function createAnonClient() {
const supabase = createSupabaseClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
{
global: {
headers: {
Authorization: Bearer ${process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY}
}
},
auth: {
autoRefreshToken: false,
persistSession: false,
detectSessionInUrl: false
}
}
);
return supabase;
}