nextjs-subscription-payments
nextjs-subscription-payments copied to clipboard
Browser Client Returns Null User.
Problem The server-side client successfully retrieves user details, but the browser client returns a null user. As a result, I am unable to display user details on the client side and must instead depend on server components at the top of the component hierarchy.
Following logs the user as null
import {createClient} from "@/utils/supabase/client";
export default async function AccountPage() {
const supabase = createClient();
const {data} = await supabase.auth.getUser()
console.log("data", data)
return <div>Account page</div>;
}
While this works
"use server";
import {createClient} from '@/utils/supabase/server';
import {getUser} from "@/utils/supabase/queries";
export default async function AccountPage() {
const supabase = createClient();
const user = await getUser(supabase);
console.log("user", user)
return <div>Account page</div>;
}
Server Side Client
import {type CookieOptions, createServerClient} from '@supabase/ssr';
import {cookies} from 'next/headers';
// Define a function to create a Supabase client for server-side operations
// The function takes a cookie store created with next/headers cookies as an argument
export const createClient = () => {
const cookieStore = cookies();
return createServerClient(
// Pass Supabase URL and anonymous key from the environment to the client
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
// Define a cookies object with methods for interacting with the cookie store and pass it to the client
{
cookies: {
// The get method is used to retrieve a cookie by its name
get(name: string) {
return cookieStore.get(name)?.value;
},
// The set method is used to set a cookie with a given name, value, and options
set(name: string, value: string, options: CookieOptions) {
try {
cookieStore.set({name, value, ...options});
} catch (error) {
// If the set method is called from a Server Component, an error may occur
// This can be ignored if there is middleware refreshing user sessions
}
},
// The remove method is used to delete a cookie by its name
remove(name: string, options: CookieOptions) {
try {
cookieStore.set({name, value: '', ...options});
} catch (error) {
// If the remove method is called from a Server Component, an error may occur
// This can be ignored if there is middleware refreshing user sessions
}
}
}
}
);
};
Client Side Client
import {createBrowserClient} from '@supabase/ssr';
// Define a function to create a Supabase client for client-side operations
export const createClient = () =>
createBrowserClient(
// Pass Supabase URL and anonymous key from the environment to the client
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);