async-storage: not working react native web

What happened?

Getting Error

Version

1.23.1

What platforms are you seeing this issue on?

  • Android
  • iOS
  • macOS
  • Windows
  • web

System Information

Error storing data ReferenceError: window is not defined
    at getValue (/node_modules/@react-native-async-storage/async-storage/lib/commonjs/AsyncStorage.js:69:52)

Steps to Reproduce

  • install async storage in expo 51
  • run web

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 14
  • Comments: 25

Most upvoted comments

For those using supabase and seeing this in the stack trace too, check out supabase/supabase-js#786

Great! I solve it by the following code.

import { AppState, Platform } from 'react-native';
import 'react-native-url-polyfill/auto';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL;
const supabaseAnonKey = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY;

if (!supabaseUrl || !supabaseAnonKey) {
  throw new Error('Supabase URL or Anon Key is not defined');
}


class SupabaseStorage {
  async getItem(key: string) {
    if (Platform.OS === "web") {
      if (typeof localStorage === "undefined") {
        return null;
      }
      return localStorage.getItem(key);
    }
    return AsyncStorage.getItem(key);
  }
  async removeItem(key: string) {
    if (Platform.OS === "web") {
      return localStorage.removeItem(key);
    }
    return AsyncStorage.removeItem(key);
  }
  async setItem(key: string, value: string) {
    if (Platform.OS === "web") {
      return localStorage.setItem(key, value);
    }
    return AsyncStorage.setItem(key, value);
  }
}

export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
  auth: {
    storage: new SupabaseStorage(),
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: false,
  },
});

I’m having the same issue… Latest expo sdk and react-native-async-storage version

some issue here with 2.0.0 version

Change the ‘output’ of the web node in ‘app. json’ from ‘static’ to ‘single’ This works for me

This issue has been marked as stale due to inactivity. Please respond or otherwise resolve the issue within 7 days or it will be closed.

localStorage ?

@adsalihac Yep, in web localStorage it’s simply the native solution. (No even need to import anything to use it)

At least, Zustand is able to deal with that seamlessly.

For those using supabase and seeing this in the stack trace too, check out https://github.com/supabase/supabase-js/issues/786

Got the exact same issue.

Using: “expo”: “^51.0.9” “@react-native-async-storage/async-storage”: “1.23.1” “redux-persist”: “^6.0.0”