Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I cant use supabse with expo, Immediately I run the web or app, It crashes immediately #1350

Open
qal-technologies opened this issue Jan 9, 2025 · 2 comments
Labels
bug Something isn't working

Comments

@qal-technologies
Copy link

It throws this error anytime I run it:

C:\Users\HomePC\Desktop\pipuApp\node_modules@expo\cli\build\src\utils\errors.js:123
throw error;
^

ReferenceError: window is not defined
at getValue (C:\Users\HomePC\Desktop\pipuApp\node_modules@react-native-async-storage\async-storage\lib\commonjs\AsyncStorage.js:63:52)
at C:\Users\HomePC\Desktop\pipuApp\node_modules@react-native-async-storage\async-storage\lib\commonjs\AsyncStorage.js:39:21
at new Promise ()
at createPromise (C:\Users\HomePC\Desktop\pipuApp\node_modules@react-native-async-storage\async-storage\lib\commonjs\AsyncStorage.js:37:10)
at Object.getItem (C:\Users\HomePC\Desktop\pipuApp\node_modules@react-native-async-storage\async-storage\lib\commonjs\AsyncStorage.js:63:12)
at getItemAsync (C:\Users\HomePC\Desktop\pipuApp\node_modules@supabase\auth-js\dist\main\lib\helpers.js:134:33)
at SupabaseAuthClient.__loadSession (C:\Users\HomePC\Desktop\pipuApp\node_modules@supabase\auth-js\dist\main\GoTrueClient.js:815:66)
at SupabaseAuthClient._useSession (C:\Users\HomePC\Desktop\pipuApp\node_modules@supabase\auth-js\dist\main\GoTrueClient.js:796:39)
at SupabaseAuthClient._emitInitialSession (C:\Users\HomePC\Desktop\pipuApp\node_modules@supabase\auth-js\dist\main\GoTrueClient.js:1242:27)
at C:\Users\HomePC\Desktop\pipuApp\node_modules@supabase\auth-js\dist\main\GoTrueClient.js:1236:22

@qal-technologies qal-technologies added the bug Something isn't working label Jan 9, 2025
@Mohammed-Yasin-Mulla
Copy link

Mohammed-Yasin-Mulla commented Jan 10, 2025

I have been facing the same issue lately.
If I console log all the .envs in the Expo app, I can read them without any issues, but the moment I try to initialise a Supabase client, I get the error saying that the Supabase URL is required.

When I develop locally using the Expo build, it works well, but when I try to build the app using Xcode or EAS, the app crashes.

I am not sure whether this is an Expo issue or a Supabase issue. I have created a project multiple times and still face this issue after some time in the project.

@martinromario55
Copy link

martinromario55 commented Jan 10, 2025

This is how I normally implement my workflow in expo:

  1. Create a supabase service
  2. Create an auth provider
  3. Wrap the Stack in your root layout with the Auth provider

Step 1: Create a supabase.ts file (anywhere you can easily access), then add the code:

import * as SecureStore from 'expo-secure-store'
import { createClient } from '@supabase/supabase-js'

const ExpoSecureStoreAdapter = {
  getItem: (key: string) => {
    return SecureStore.getItemAsync(key)
  },
  setItem: (key: string, value: string) => {
    SecureStore.setItemAsync(key, value)
  },
  removeItem: (key: string) => {
    SecureStore.deleteItemAsync(key)
  },
}

const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL as string
const supabaseAnonKey = process.env.EXPO_PUBLIC_SUPABASE_KEY as string

export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
  auth: {
    storage: ExpoSecureStoreAdapter as any,
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: false,
  },
})```


Step 2: Setup Supabase Auth Provider:

```import { supabase } from '@/lib/supabase'
import { Session } from '@supabase/supabase-js'
import {
  createContext,
  PropsWithChildren,
  useContext,
  useEffect,
  useState,
} from 'react'

type AuthData = {
  session: Session | null
  loading: boolean
  profile: any
  isAdmin: boolean
}

const AuthContext = createContext<AuthData>({
  session: null,
  loading: true,
  profile: null,
  isAdmin: false
})

export default function AuthProvider({ children }: PropsWithChildren) {
  const [session, setSession] = useState<Session | null>(null)
  const [profile, setProfile] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchSession = async () => {
      const {
        data: { session },
        error,
      } = await supabase.auth.getSession()

      if (error) {
        console.error('Error fetching session:', error)
      }

      setSession(session)

      if (session) {
        const { data } = await supabase
          .from('profiles')
          .select('*')
          .eq('id', session.user.id)
          .single()

        setProfile(data || null)
      }

      setLoading(false)
    }

    fetchSession()

    supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session)
    })
  }, [])
  return (
    <AuthContext.Provider value={{ session, loading, profile, isAdmin: profile?.group === "ADMIN" }}>
      {children}
    </AuthContext.Provider>
  )
}

export const useAuth = () => useContext(AuthContext)```


Step 3: Wrap the provider in the Root Layout

`import AuthProvider from "@/providers/auth-providers";
import {  Stack } from "expo-router";


const RootLayout = () => {

return (
<AuthProvider>
<Stack>
<Stack.Screen  />
...
<Stack>
</AuthProvider>
)
}

export default RootLayout;
`

Supabase service usage:

`
import { supabase } from '@/lib/supabase'

...

const fetchProducts = async () => {
const { data, error } = await supabase.from('products').select('*')

...
}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants