supabase / supabase-js

An isomorphic Javascript client for Supabase. Query your Supabase database, subscribe to realtime events, upload and download files, browse typescript examples, invoke postgres functions via rpc, invoke supabase edge functions, query pgvector.
https://supabase.com
MIT License
2.86k stars 220 forks source link

[AuthRetryableFetchError: Network request failed] on signIn #675

Open LucaCevasco opened 1 year ago

LucaCevasco commented 1 year ago

Bug report

Describe the bug

I have an app in react native with expo, when I try to do a sign-in with supabase.auth.signInWithPassword, it throws an unhandled error with [AuthRetryableFetchError: Network request failed]. This only happens in android, emulator and physical device. not in iOS.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

call supabase.auth.signInWithPassword in android expo app.

expo SDK v47 supabase js v2.2.2

Expected behavior

It should login normally

System information

Additional context

atanaskanchev commented 1 year ago

@LucaCevasco have you managed to resolve that issue? I am getting the same, only on Android:

 "error": {
    "name": "AuthRetryableFetchError",
    "message": "Network request failed",
    "status": 0
  }

supabase-js: 2.4.1

aismartchat commented 8 months ago

Same problem both with iOS and Android Simulator.

hf commented 8 months ago

Can you please make sure that the app and device actually has internet. Make sure the app also has the required internet permission (that needs to be explicitly granted in Android).

amankumarm commented 7 months ago

have the same issue, using expo, internet permission is given by default

emmyduruc commented 7 months ago

i am having same issue on real device (android) ios stimulator works fine

maxwowo commented 7 months ago

Also having the same issue on Android emulator with expo@49.0.13 and @supabase/supabase-js@2.38.0. Also checked that both <uses-permission android:name="android.permission.INTERNET"/> (app can use internet) and android:usesCleartextTraffic="true" (app can access non HTTPS endpoints) are in AndroidManifest.xml, so the issue is likely to be Supabase client related 🤔

FxBresson commented 7 months ago

Commenting here because I'm also having the issue but on iOS as well ! "expo": "^49.0.11" "@supabase/supabase-js": "^2.33.2"

NorseGaud commented 6 months ago

I get these even without signing in. Emulator has internet because I can sign into google.

Metro log:

 ERROR  [TypeError: Network request failed]
 ERROR  [AuthRetryableFetchError: Network request failed]
 ERROR  [TypeError: Network request failed]
 ERROR  [AuthRetryableFetchError: Network request failed]
 ERROR  [TypeError: Network request failed]
 ERROR  [AuthRetryableFetchError: Network request failed]
 ERROR  [TypeError: Network request failed]
 ERROR  [TypeError: Network request failed]
 ERROR  [TypeError: Network request failed]
Screenshot 2023-11-09 at 2 14 20 PM

The code:

 import React, { useState } from 'react'
import { Alert, StyleSheet, View } from 'react-native'
import { supabase } from 'src/db/supabase'
import { Button, Input } from 'react-native-elements'
import {
  GoogleSignin,
  GoogleSigninButton,
  statusCodes,
} from '@react-native-google-signin/google-signin'

export default function Auth() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
    GoogleSignin.configure({
    scopes: [
            'openid',
            'profile',
            'email',
            "https://www.googleapis.com/auth/drive",
            "https://www.googleapis.com/auth/spreadsheets",
        ],
    webClientId: '[dedacted]',
  })

  async function signInWithEmail() {
    setLoading(true)
    const { error } = await supabase.auth.signInWithPassword({
      email: email,
      password: password,
    })

    if (error) Alert.alert(error.message)
    setLoading(false)
  }

  async function signUpWithEmail() {
    setLoading(true)
    const {
      data: { session },
      error,
    } = await supabase.auth.signUp({
      email: email,
      password: password,
    })

    if (error) Alert.alert(error.message)
    // if (!session) Alert.alert('Please check your inbox for email verification!')
    setLoading(false)
  }

  return (
    <View style={styles.container}>
            <GoogleSigninButton
                size={GoogleSigninButton.Size.Wide}
                color={GoogleSigninButton.Color.Dark}
                onPress={async () => {
                    try {
                        await GoogleSignin.hasPlayServices()
                        const userInfo = await GoogleSignin.signIn()
                        if (userInfo.idToken) {
                            const { data, error } = await supabase.auth.signInWithIdToken({
                                provider: 'google',
                                token: userInfo.idToken,
                            })
                            console.log(error, data)
                        } else {
                            throw new Error('no ID token present!')
                        }
                    } catch (error) {
                        if (error.code === statusCodes.SIGN_IN_CANCELLED) {
                            // user cancelled the login flow
                        } else if (error.code === statusCodes.IN_PROGRESS) {
                            // operation (e.g. sign in) is in progress already
                        } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
                            // play services not available or outdated
                        } else {
                            // some other error happened
                        }
                    }
                }}
            />
      <View style={[styles.verticallySpaced, styles.mt20]}>
        <Input
          label="Email"
          leftIcon={{ type: 'font-awesome', name: 'envelope' }}
          onChangeText={(text) => setEmail(text)}
          value={email}
          placeholder="email@address.com"
          autoCapitalize={'none'}
        />
      </View>
      <View style={styles.verticallySpaced}>
        <Input
          label="Password"
          leftIcon={{ type: 'font-awesome', name: 'lock' }}
          onChangeText={(text) => setPassword(text)}
          value={password}
          secureTextEntry={true}
          placeholder="Password"
          autoCapitalize={'none'}
        />
      </View>
      <View style={[styles.verticallySpaced, styles.mt20]}>
        <Button title="Sign in" disabled={loading} onPress={() => signInWithEmail()} />
      </View>
      <View style={styles.verticallySpaced}>
        <Button title="Sign up" disabled={loading} onPress={() => signUpWithEmail()} />
      </View>
    </View>
  )
}
NorseGaud commented 6 months ago

Ok, my .env had the wrong supabase.co url and anon key. Fixing that an fully re-installing the app in the emulator fixed it.

elvc commented 5 months ago

Having the same issue with these dependencies

"dependencies": {
    "@react-native-async-storage/async-storage": "1.18.2",
    "@supabase/supabase-js": "^2.39.0",
    "expo": "~49.0.15",
    "expo-status-bar": "~1.6.0",
    "react": "18.2.0",
    "react-native": "0.72.6",
    "react-native-elements": "^3.4.3",
    "react-native-url-polyfill": "^2.0.0",
    "expo-auth-session": "~5.0.2",
    "expo-crypto": "~12.4.1"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@types/react": "~18.2.14",
    "typescript": "^5.1.3"
  },
swyxio commented 4 months ago

hi gang

reason 1 - connecting to supabase hosted db that has been suspended

for me the AuthRetryableFetchError happened when it was connected to a suspended database i hadnt touched in a while (curse you @awalias!!!). when i went back to dashboard, and woke it back up again, it didnt start working immediately, but after like ~3 mins wait i was able to get it working again without once touching my code.

TLDR check that your database hasnt been suspended because you havent been working hard enough

edit: reason 2 - trying to connect to local supabase db that isn't running

came back to also say i got the same error but trying to connect to http://127.0.0.1:54321/ (supabase's default local host/port) after the holidays. took a second to realize i hadn't run npx supabase start.

isaachinman commented 4 months ago

Just ran into this. Definitely not an issue of incorrect config, as my Expo app runs fine on iOS and Android dev and simulator builds. However, when building a staging app, Supabase logins start to fail, only on Android with:

AuthRetryableFetchError
Value is undefined, expected a String

Was anyone able to solve this?

isaachinman commented 4 months ago

I have not gotten all the way to the bottom of this issue, but have made progress.

After digging into the @supabase/supabase-js source, and checking out how AuthRetryableFetchError is used, it became clear to me that whatever was happening was due to a failed network request in some Android runtimes.

To validate this theory, I installed axios and modified my code as such:

export const supabaseClient = createClient(
  config.supabase.url,
  config.supabase.anonKey,
  {
    auth: {
      autoRefreshToken: true,
      detectSessionInUrl: false,
      persistSession: true,
      storage,
    },
    global: {
      fetch: async (url, config) =>{
        const result = await axios({
          headers: config?.headers,
          method: config?.method,
          url,
        })

        const responseBody = typeof result.data === 'object' ? JSON.stringify(result.data) : result.data

        const headers = new Headers()
        Object.entries(result.headers).forEach(([key, value]) => {
          headers.append(key, value)
        })

        return new Response(responseBody, {
          headers,
          status: result.status,
          statusText: result.statusText,
        })
      },
    },
  },
)

Basically, swapped the fetch instance for axios, but crucially all else is exactly the same.

This fixed worked. Something is broken with either:

  1. RN fetch implementation in Android 13/14
  2. @supabase/supabase-js's use of fetch in general

Not sure yet which it is!

isaachinman commented 4 months ago

Found it. I previously had another polyfill in my entry point:

import 'react-native-polyfill-globals/auto'

I added this for streaming support. As soon as this line is removed, @supabase/supabase-js works. Hope this helps anyone else. Lost a couple hours on this!

Atomic71 commented 3 months ago

I had exactly this same problem when my macbook was auto-restarted (for whatever reason)

When I turned on docker, I was surprised to see supabase instance still running. And I was running into the, couldn't figure it out for like 15 minutes, thought it was config or something.

AuthRetryableFetchError: Network request failed

However, reading this thread made me do stop/start cycle (with npx supabase), and my problems were over.

apple-blossom commented 3 months ago
"@supabase/supabase-js": "^2.38.4",
"expo": "~49.0.15",
"react": "18.2.0",
"react-native": "0.72.6",

Have same issue on physical device (Android 14), but works fine on Android emulator (Android 14)

andrisole92 commented 2 months ago

I have not gotten all the way to the bottom of this issue, but have made progress.

After digging into the @supabase/supabase-js source, and checking out how AuthRetryableFetchError is used, it became clear to me that whatever was happening was due to a failed network request in some Android runtimes.

To validate this theory, I installed axios and modified my code as such:

export const supabaseClient = createClient(
  config.supabase.url,
  config.supabase.anonKey,
  {
    auth: {
      autoRefreshToken: true,
      detectSessionInUrl: false,
      persistSession: true,
      storage,
    },
    global: {
      fetch: async (url, config) =>{
        const result = await axios({
          headers: config?.headers,
          method: config?.method,
          url,
        })

        const responseBody = typeof result.data === 'object' ? JSON.stringify(result.data) : result.data

        const headers = new Headers()
        Object.entries(result.headers).forEach(([key, value]) => {
          headers.append(key, value)
        })

        return new Response(responseBody, {
          headers,
          status: result.status,
          statusText: result.statusText,
        })
      },
    },
  },
)

Basically, swapped the fetch instance for axios, but crucially all else is exactly the same.

This fixed worked. Something is broken with either:

  1. RN fetch implementation in Android 13/14
  2. @supabase/supabase-js's use of fetch in general

Not sure yet which it is!

Did not work for me :/

FxBresson commented 2 months ago

Ok, my .env had the wrong supabase.co url and anon key. Fixing that an fully re-installing the app in the emulator fixed it.

I had the same issue, I really lost a couple of hours trying to fix the problem while it was my env variable that were false all along. Make sure they're correct, it might be your case also ! 🙏

ovidb commented 1 month ago

If, like me, you are developing against the local instance of supabase you might have something like this in your env

SUPABASE_URL=http://127.0.0.1:54321

If you're using a mobile device, when supabase-js is instantiated with that address it will fail as now it points to the mobile device instead of your development machine.

Solution: Get your local network IP from you development machine and use it as your SUPABASE_URL

SUPABASE_URL=http://192.168.1.111:54321

To get your local network IP address you can do quick google, but for me on mac is the following:

ipconfig getifaddr en0 

(could also be en1 or en2 if you use ethernet)

PaperPrototype commented 2 weeks ago

I had a similar problem and I managed to crack the error down to the Auth logs

Screenshot 2024-04-28 at 2 09 18 AM Screenshot 2024-04-28 at 12 44 50 PM
KnightOfNih commented 1 week ago

If, like me, you are developing against the local instance of supabase you might have something like this in your env

SUPABASE_URL=http://127.0.0.1:54321

If you're using a mobile device, when supabase-js is instantiated with that address it will fail as now it points to the mobile device instead of your development machine.

Solution: Get your local network IP from you development machine and use it as your SUPABASE_URL

SUPABASE_URL=http://192.168.1.111:54321

To get your local network IP address you can do quick google, but for me on mac is the following:

ipconfig getifaddr en0 

(could also be en1 or en2 if you use ethernet)

Running expo go emulator against a local supabase instance and this was the issue for me. Changing from localhost to my ip address worked.