Replies: 2 comments 3 replies
-
I've also tried conditional importing, but that also doesn't work: import isServer from "@/utils/isServer";
const supabaseClient = isServer()
? import("@/services/supabase/clients/server").then(
(module) => module.default
)
: import("@/services/supabase/clients/browser").then(
(module) => module.default
);
export default supabaseClient; |
Beta Was this translation helpful? Give feedback.
-
Hey, I was thinking about this, and I came up with an idea that might work for your situation. Instead of splitting things into separate files, you can use a single function to handle both import { createBrowserClient, createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
export async function createClient() {
const isServer = typeof window === 'undefined' // Check if we're on the server
if (isServer) {
// Server-side logic
const cookieStore = cookies()
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) => {
cookieStore.set(name, value, options)
})
} catch {
// If it's running in a Server Component, just ignore
}
},
},
}
)
} else {
// Client-side logic
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
}
} The idea here is to check It seems like it should work, but I haven’t tested it extensively, so let me know if it gives you any trouble or if you find a better way! Just thought it might simplify things by keeping everything in one place. 😊 |
Beta Was this translation helpful? Give feedback.
-
So I'm using
@supabase/ssr
to handle SSR with NextJS.I like to keep my API functions centralised into one api folder/file, so that I don't have to go looking for different queries in different components. The issue I ran into right now is that for every request, I have to create two separate versions that each use either
createServerClient
orcreateBrowserClient
.I obviously don't want to keep doing this because it's too much overhead for no reason, so I thought let's conditionally check for
isServer ? createServerClient : createBrowserClient
. The problem is that mycreateServerClient
also imports cookies from Next (import { cookies } from "next/headers";
), which causes an error any time I try to import thecreateServerClient
client anywhere that is not server-compatible (because it depends thecookies
modules).I don't know what to do now, the only solution I can think of is to pass the client to every API function as a parameter, but I just find that so cumbersome and it feels like there has to be a better/more efficient way. I hope anyone has a better solution!
Beta Was this translation helpful? Give feedback.
All reactions