Where does authentication fit in a React Native app?

17 May 2017

In a web app, you could use cookies or store a token in a localStorage…

But how do you keep a user logged in in your React Native app?

But first… let’s zoom out a little and rehash what developers commonly mean when they say “auth” in terms of a user-facing application:

Most often, authentication is done using tokens.

The concept of token authentication is not limited to React Native apps, however; native mobile and desktop apps, as well as many web apps, all make use of tokens.

In simple terms, token authentication means this:

Instead of passing username and password with each request to the server, we pass in some random-ish string along with each request, called a token. We obtain this token by making a “login” request to the server with username and password.

A way for the user to sign in

The user has to prove us they are who they say they are, usually by entering their username and password. The UI that makes that happen is not the point, though, as it will vary by application.

The most certain thing at this stage is: we will use the entered username and password to ask the server to give us a token.

A way to save the user’s session

Life wouldn’t be fun if, every time you opened the Twitter app, you had to enter your credentials all over again.

Web apps have it easy: there are cookies, and then there’s also localStorage.

Say we have a token that we want to save. What do you do in a React Native app, though?

Two options:

A way to let the server know who the user is

This is usually achieved by passing the token using headers, for example.

Like in a browser environment, you can use fetch in React Native. And sending headers with fetch is pretty easy:

// assuming `token` is already fetched somehow

const headers = {
  Authentication: `Bearer ${token}`,

fetch(path, { method: 'GET', headers: headers }).then(...);

Think your friends would dig this article, too?

If you need a mobile app built for your business or your idea, there's a chance I could help you with that.
Leave your email here and I will get back to you shortly.