Persistent User Authentication in React Native with AsyncStorage Not Working

I’m developing a React Native app where I need to persist user authentication across app restarts. I’m using AsyncStorage to store the session token. Logging in works fine, but when I close the app and reopen it, the user is logged out and needs to log in again (btw it is my first react native project).

Here are the key parts of my implementation:

API and Auth Utilities ( I am using django-allauth lib, which is working fine in react, but now i want to use it in react native not working):

import AsyncStorage from "@react-native-async-storage/async-storage";

const Client = Object.freeze({
  APP: "app",
  BROWSER: "browser",
});

const CLIENT = Client.APP;

const BASE_URL = `http://localhost:7013/_allauth/${CLIENT}/v1`;
const ACCEPT_JSON = {
  Accept: "application/json",
  "Content-Type": "application/json",
};

export const URLs = Object.freeze({
  // Meta
  CONFIG: BASE_URL + "/config",

  // Auth: Basics
  LOGIN: BASE_URL + "/auth/login",
  SESSION: BASE_URL + "/auth/session",
  SIGNUP: BASE_URL + "/auth/signup",

  // Auth: Sessions
  SESSIONS: BASE_URL + "/auth/sessions",
});

export const AuthenticatorType = Object.freeze({
  TOTP: "totp",
  RECOVERY_CODES: "recovery_codes",
});

// Function to retrieve CSRF token
async function getCSRFToken() {
  try {
    const csrfToken = await AsyncStorage.getItem("csrfToken");
    return csrfToken;
  } catch (error) {
    console.error("Error retrieving CSRF token:", error);
    return null;
  }
}

async function request(method, path, data, headers = {}) {
  try {
    const options = {
      method,
      headers: {
        ...ACCEPT_JSON,
        ...headers,
      },
    };

    // Don't pass authentication related headers to the logout endpoint
    if (path !== URLs.LOGOUT) {
      const csrfToken = await getCSRFToken();
      if (csrfToken) {
        options.headers["X-CSRFToken"] = csrfToken;
      }
    }

    if (typeof data !== "undefined") {
      options.body = JSON.stringify(data);
    }

    const response = await fetch(path, options);
    const result = await response.json();

    // Handle session token updates and authentication state changes
    if (response.ok && result.session_token) {
      await AsyncStorage.setItem("sessionToken", result.session_token);
    }

    return result;
  } catch (error) {
    console.error("Request failed:", error);
    throw error;
  }
}
export async function login(data) {
  return await request("POST", URLs.LOGIN, data);
}

export async function logout() {
  return await request("DELETE", URLs.SESSION);
}

export async function signUp(data) {
  return await request("POST", URLs.SIGNUP, data);
}

export async function getConfig() {
  return await request("GET", URLs.CONFIG);
}

export async function getAuth() {
  return await request("GET", URLs.SESSION);
}

Global Provider (which is working with appwrite as well):

import React, { createContext, useContext, useEffect, useState } from "react";

import { getAuth } from "@/lib/allauth";

const GlobalContext = createContext();
export const useGlobalContext = () => useContext(GlobalContext);

const GlobalProvider = ({ children }) => {
  const [isLogged, setIsLogged] = useState(false);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchCurrentUser = async () => {
      try {
        const res = await getAuth();
        console.log("provider auth");
        console.log(res);
        if (res && res.status === 200 && res.meta.is_authenticated) {
          setIsLogged(true);
          setUser(res.data.user);
        } else {
          setIsLogged(false);
          setUser(null);
        }
      } catch (error) {
        console.error("Error fetching authentication status:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchCurrentUser();
  }, []);

  return (
    <GlobalContext.Provider
      value={{
        isLogged,
        setIsLogged,
        user,
        setUser,
        loading,
      }}
    >
      {children}
    </GlobalContext.Provider>
  );
};

export default GlobalProvider;


and main layouot:

import { useEffect } from "react";
import { useFonts } from "expo-font";
import "react-native-url-polyfill/auto";
import { SplashScreen, Stack } from "expo-router";

import GlobalProvider from "@/context/GlobalProvider";

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();

const RootLayout = () => {
  const [fontsLoaded, error] = useFonts({
    "Poppins-Black": require("../assets/fonts/Poppins-Black.ttf"),
    "Poppins-Bold": require("../assets/fonts/Poppins-Bold.ttf"),
    "Poppins-ExtraBold": require("../assets/fonts/Poppins-ExtraBold.ttf"),
    "Poppins-ExtraLight": require("../assets/fonts/Poppins-ExtraLight.ttf"),
    "Poppins-Light": require("../assets/fonts/Poppins-Light.ttf"),
    "Poppins-Medium": require("../assets/fonts/Poppins-Medium.ttf"),
    "Poppins-Regular": require("../assets/fonts/Poppins-Regular.ttf"),
    "Poppins-SemiBold": require("../assets/fonts/Poppins-SemiBold.ttf"),
    "Poppins-Thin": require("../assets/fonts/Poppins-Thin.ttf"),
  });

  useEffect(() => {
    if (error) throw error;

    if (fontsLoaded) {
      SplashScreen.hideAsync();
    }
  }, [fontsLoaded, error]);

  if (!fontsLoaded) {
    return null;
  }

  if (!fontsLoaded && !error) {
    return null;
  }

  return (
    <GlobalProvider>
      <Stack>
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        <Stack.Screen name="(auth)" options={{ headerShown: false }} />
        <Stack.Screen name="index" options={{ headerShown: false }} />
        <Stack.Screen name="search/[query]" options={{ headerShown: false }} />
      </Stack>
    </GlobalProvider>
  );
};

export default RootLayout;

Finaly the Login Component:

import { useState } from "react";
import { Link, router } from "expo-router";
import { SafeAreaView } from "react-native-safe-area-context";
import { View, Text, ScrollView, Dimensions, Alert, Image } from "react-native";

import { images } from "@/constants";
import { CustomButton, FormField } from "@/components";
// import { getCurrentUser, signIn } from "@/lib/appwrite";
import { login } from "@/lib/allauth";
import { useGlobalContext } from "@/context/GlobalProvider";

const SignIn = () => {
  const { setUser, setIsLogged } = useGlobalContext();
  const [isSubmitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    email: "",
    password: "",
  });

  const submit = async () => {
    if (form.email === "" || form.password === "") {
      Alert.alert("Error", "Please fill in all fields");
      return;
    }

    setSubmitting(true);

    try {
      const result = await login({
        email: form.email,
        password: form.password,
      });

      if (result && result.status === 200 && result.meta.is_authenticated) {
        console.log("login");
        console.log(result);
        setUser(result.data.user);
        setIsLogged(true);
        Alert.alert("Success", "User signed in successfully");
        router.replace("/home");
      } else {
        Alert.alert("Error", "Invalid login credentials");
      }
    } catch (error) {
      Alert.alert("Error", error.message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SafeAreaView className="bg-primary h-full">
      <ScrollView>
        <View
          className="w-full flex justify-center h-full px-4 my-6"
          style={{
            minHeight: Dimensions.get("window").height - 100,
          }}
        >
          <Image
            source={images.logo}
            resizeMode="contain"
            className="w-[115px] h-[34px]"
          />

          <Text className="text-2xl font-semibold text-white mt-10 font-psemibold">
            Log in to SmartTime
          </Text>

          <FormField
            title="Email"
            value={form.email}
            handleChangeText={(e) => setForm({ ...form, email: e })}
            otherStyles="mt-7"
            keyboardType="email-address"
          />

          <FormField
            title="Password"
            value={form.password}
            handleChangeText={(e) => setForm({ ...form, password: e })}
            otherStyles="mt-7"
          />

          <CustomButton
            title="Sign In"
            handlePress={submit}
            containerStyles="mt-7"
            isLoading={isSubmitting}
          />

          <View className="flex justify-center pt-5 flex-row gap-2">
            <Text className="text-lg text-gray-100 font-pregular">
              Don't have an account?
            </Text>
            <Link
              href="/signup"
              className="text-lg font-psemibold text-secondary"
            >
              Signup
            </Link>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default SignIn;

Problem:

When I log in, it works, but when I close or refresh the app, I need to log in again. I want the user to stay logged in.

Steps I’ve Taken:

Stored the session token in AsyncStorage upon login.
Checked for the session token on app launch in the GlobalProvider component.
Authenticated the user using the session token if it exists.

What could be going wrong? How can I ensure the user stays logged in across app restarts?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật