Reputation: 529
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.
Upvotes: 2
Views: 986
Reputation: 143
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!
Upvotes: 4