How do keep users logged into my app when they close it

Right now once you’ve logged into my app. If you close it, you get logged out.
How do I keep users logged in?

1 Like

Hey @omorhefere,

A common method is saving the user’s credentials with AsyncStorage after they successfully log in and then fetching them when the app loads up so they don’t have to enter them in each time.




When you log a user in, presumably you’re getting some information back, like an API token or a session cookie, that is then attached to subsequent requests (usually in the HTTP header) to tie the request back to the original successful login. You need to save that piece of information so it can be used on future requests even when the app is closed and reopened.

If your API uses session cookies, and your login request returns a Set-Cookie header in your response, no further work is needed on your part. That cookie will then be persisted automatically.

If your API uses a token, or uses a cookie but doesn’t send back a Set-Cookie header, you need to save that, and then restore it next time the app opens and start attaching it to HTTP requests (the fetch API lets you add HTTP headers). You can save that in AsyncStorage (or SecureStore might be better

Of course, just because you save the cookie doesn’t mean the user will not see the login screen. If your first view is always the login screen, then your users will always see the login screen. You need to program your app to, say, assume the user is always logged in, make a request for data, and then kick the user back to the login screen if the request fails due to the user being unauthorized (e.g., a 401 error).

If you have to store an actual username and password, SecureStore would probably be the way to go (, because at least its encrypted. However, it’s usually unnecessary for an app to store an actual username and password. If you never store the username and password, then you never risk leaking it. If you leak a username and password, it could leak access to many other apps the user logs into to an attacker. If you leak an API token, all you’ve exposed is access to your app. So it’s much safer to never store a username or password.

One thing that helped me a lot with this is playing with the requests in Postman. Whatever you need to attach to a Postman request is what you need to save.


This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.