Search code examples
javascriptreactjsexpressreduxpassport-local-mongoose

How to use redux for user authentication?


Hello everyone. I studied and studied at MERN. I also created a project. Now I don’t believe what I did was right. Now that matters to me. Sorry my english:)
I have seen many projects on the internet, but the method used in most of them did not match mine. For example many people use jwt for authentication. But I use passportjs and passport-local-mongoose. I successfully registered and loginned in backen(express). In frontend every component I used action ( redux ) for get user information loginned or not like this:

    UseEffect( ()=>{
      User_Auth(12); // why 12? If I didnt write this value 
                     // action cannot work but when I put work 
                     // well and this value I cant do with.
} )

This methog is true? If you want to see this simple project please see this: https://github.com/Feruz00/login_register/tree/master
Thanks


Solution

  • Authentication in Redux

    Authentication is essential to any real application. When going about authentication you must keep in mind that nothing changes with how you should organize your application and you should implement authentication in the same way you would any other feature. It is relatively straightforward:

    1. Create action constants for LOGIN_SUCCESS, LOGIN_FAILURE, etc.
    2. Create action creators that take in credentials, a flag that signifies whether authentication succeeded, a token, or an error message as the payload.
    3. Create an async action creator with Redux Thunk middleware or any middleware you see fit to fire a network request to an API that returns a token if the credentials are valid. Then save the token in the local storage or show a response to the user if it failed. You can perform these side effects from the action creators you wrote in the previous step.
    4. Create a reducer that returns the next state for each possible authentication case (LOGIN_SUCCESS, LOGIN_FAILURE, etc).

    EXAMPLE: https://github.com/joshgeller/react-redux-jwt-auth-example

    SOURCE: https://redux.js.org/faq/miscellaneous