2

What are the best libraries should I be using for node js + react-native authentication? I was using passport local strategy with ejs templates for the login/register page because I was building a web app. Now I am working on mobile application, I don't know how this is going to work on a mobile app. Any ideas on how can I start this?

Thanks in advance.

1 Answer 1

4

The following is how I implement authentication in my react-native applications with node js backend. I use jwt tokens, where I store the user's token inside the device using expo's secure storage library. Then following the recommended auth flow by react-native-navigation documentation, whenever the app starts I check whether the token is present and return corresponding navigation stack. Refer to the code below for implementation.

LoginScreen.js/RegisterScreen.js

//...

// Get token from your backend and save it in secure storage
const userToken = request.data.token
try {
    await SecureStore.setItemAsync("token", userToken);
  } catch (error) {
    console.warn(error);
 }
 
 // ...

App.js

export default function App() {
  const [isReady, setIsReady] = useState(false)
  const [userToken, setUserToken] = useState();
  
  // Fetch token and set state
  const restoreUser = async () => {
     const token = await SecureStore.getItemAsync("token")
     setUserToken(token)
  }
  
  if (!isReady)
    // Show splash screen while checking for userToken
    return (
      <AppLoading
        startAsync={restoreUser}
        onFinish={() => setIsReady(true)}
        onError={console.warn}
      />
    );
  
  return (
  <Stack.Navigator>
    {userToken == null ? (
      // No token found, user isn't signed in
      <Stack.Screen
        name="SignIn"
        component={SignInScreen}
        options={{
          title: 'Sign in',
          // When logging out, a pop animation feels intuitive
          // You can remove this if you want the default 'push' animation
          animationTypeForReplace: state.isSignout ? 'pop' : 'push',
        }}
      />
    ) : (
      // User is signed in
      <Stack.Screen name="Home" component={HomeScreen} />
    )}
  </Stack.Navigator>
);
  
}

On the backend take a look at jsonwebtoken npm package to see how to create jwt tokens. Goodluck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.