supabase-js icon indicating copy to clipboard operation
supabase-js copied to clipboard

[AuthRetryableFetchError: Network request failed] on signIn

Open LucaCevasco opened this issue 2 years ago • 38 comments

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

  • Version of supabase-js: 2.2.2

Additional context

LucaCevasco avatar Jan 03 '23 16:01 LucaCevasco

@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

atanaskanchev avatar Jan 21 '23 21:01 atanaskanchev

Same problem both with iOS and Android Simulator.

aismartchat avatar Sep 02 '23 18:09 aismartchat

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).

hf avatar Sep 18 '23 14:09 hf

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

amankumarm avatar Oct 10 '23 18:10 amankumarm

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

emmyduruc avatar Oct 15 '23 17:10 emmyduruc

Also having the same issue on Android emulator with [email protected] and @supabase/[email protected]. 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 🤔

maxwowo avatar Oct 16 '23 00:10 maxwowo

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

FxBresson avatar Oct 16 '23 13:10 FxBresson

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 protected]"
         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 avatar Nov 09 '23 19:11 NorseGaud

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.

NorseGaud avatar Nov 09 '23 19:11 NorseGaud

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"
  },

elvc avatar Dec 12 '23 07:12 elvc

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.

swyxio avatar Jan 04 '24 21:01 swyxio

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 avatar Jan 15 '24 19:01 isaachinman

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 avatar Jan 15 '24 21:01 isaachinman

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!

isaachinman avatar Jan 15 '24 21:01 isaachinman

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.

Atomic71 avatar Feb 02 '24 19:02 Atomic71

"@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)

apple-blossom avatar Feb 05 '24 21:02 apple-blossom

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 :/

andrisole92 avatar Feb 23 '24 20:02 andrisole92

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 ! 🙏

FxBresson avatar Feb 28 '24 22:02 FxBresson

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)

ovidb avatar Apr 07 '24 15:04 ovidb

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

PaperPrototype avatar Apr 28 '24 21:04 PaperPrototype

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.

KnightOfNih avatar May 06 '24 22:05 KnightOfNih

I fixed the issue by reinstalling all the packages

14790897 avatar Jun 02 '24 03:06 14790897

I have had the same issue

 ERROR  [TypeError: Network request failed]
 LOG  ------------------- [AuthRetryableFetchError: Network request failed]

I fixed the issue by reinstalling all the packages but did work.

:(

nguyentrancong avatar Jun 10 '24 09:06 nguyentrancong

npx supabase db reset

didn't work.

However:

npx supabase stop

then

npx supabase start

fixed it.

J

jdgamble555 avatar Jun 17 '24 00:06 jdgamble555

Just adding to this knowledge base. I am on supabase flutter 2.5.6. On flutter, if --web-hostname 0.0.0.0 is specified when running the flutter app along with supabase instance running, then they are in conflict with each other. Removing the --web-hostname 0.0.0.0 resolves the issue.

sapphire008 avatar Jun 18 '24 22:06 sapphire008

Also facing this issue

"dependencies": {
    "@apollo/client": "^3.10.8",
    "@expo/vector-icons": "^14.0.0",
    "@react-native-async-storage/async-storage": "1.23.1",
    "@react-navigation/drawer": "^6.6.15",
    "@react-navigation/native": "^6.0.2",
    "@supabase/supabase-js": "2.39.7",
    "@tamagui/config": "^1.102.2",
    "expo": "^51.0.23",
    "expo-font": "~12.0.7",
    "expo-linking": "~6.3.1",
    "expo-router": "~3.5.19",
    "expo-splash-screen": "~0.27.5",
    "expo-status-bar": "~1.12.1",
    "expo-system-ui": "~3.0.6",
    "expo-web-browser": "~13.0.3",
    "graphql": "^16.9.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.74.3",
    "react-native-gesture-handler": "~2.16.1",
    "react-native-reanimated": "~3.10.1",
    "react-native-safe-area-context": "4.10.5",
    "react-native-screens": "3.31.1",
    "react-native-svg": "15.2.0",
    "react-native-svg-transformer": "^1.4.0",
    "react-native-url-polyfill": "^2.0.0",
    "react-native-web": "~0.19.10",
    "tamagui": "^1.102.2",
    "zustand": "^4.5.4"
  },```

jIrwinCline avatar Jul 30 '24 07:07 jIrwinCline

I'm facing the same issue with Supabase installed locally with Docker and an apk deployed on my Android device. From what the doc says i'm supposed to use port 8000 for SUPABASE_URL but it only works in Expo Go. I already restarted my instance and tried a couple network ports for the URL without success.

Also i tried to track which port was used for the app by installing a mobile firewall but it looks like my app doesn't try to reach internet as the firewall doesn't detect anything from my app.

Das-ist-gutt avatar Jul 30 '24 11:07 Das-ist-gutt

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!

This worked for me, although I had to adjust it slightly:

export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
  auth: {
    storage: AsyncStorage,
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: false,
  },
  global: {
    fetch: async (url, config) => {
      try {
        const result = await axios({
          url: url as string,
          method: config?.method,
          headers: config?.headers,
          data: config?.body,
        });

        const responseBody = JSON.stringify(result.data);

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

        return new Response(responseBody, {
          headers,
          status: result.status,
          statusText: result.statusText,
        });
      } catch (error) {
        return new Response(
          JSON.stringify({
            message: error.message,
            name: error.name,
            status: error.response?.status || 500,
          }),
          {
            status: error.response?.status || 500,
            statusText: error.message,
          },
        );
      }
    },
  },
});

neb-b avatar Aug 22 '24 21:08 neb-b

@neb-b solution worked for me (using tauri. probably same issue as fetch)

benbonnet avatar Sep 23 '24 12:09 benbonnet

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)

Thanks so much for this man. I've spent nearly 12 hrs debugging this.

NOTE: Don't forget to prefix the ip address with http:// and suffix it with the :54321, that is for example: http://192.168.1.111:54321.

If I had taken note of the prefix and suffix, I wouldn't have even spent up to an hour on this.

I'm using Ubuntu 24.04 LTS and connected my system and android device through a wifi network, this is how I got my IP address:

  • Open Settings: Click on the system menu in the top-right corner of your screen and select “Settings.”

  • Navigate to Wi-Fi: In the left sidebar, click on “Wi-Fi.”

  • View Connection Details: Click on the gear icon next to the connected Wi-Fi network. A pop-up window will appear showing detailed information, including your IP address.

The ip address to use is the IPv4 address.

onyedikachi23 avatar Sep 26 '24 01:09 onyedikachi23