Unlocking the Power of JWT Authentication in MERN Apps

The Final Piece of the Puzzle

In our previous articles, we’ve built a solid foundation for a full-stack MERN app using JWT authentication. Now, it’s time to bring everything together and create a seamless user experience.

Creating a User-Friendly Endpoint

To start, we’ll create a new endpoint for users to sign in. This will involve editing our server.js file and adding a new route. We’ll also create a sample store for users, where we’ll store key-value pairs for each user.

Validating Users on the Server-Side

Next, we’ll focus on validating users on the server-side. We’ll check if the user is present in our system and validate their password. If the user isn’t found or the credentials are incorrect, we’ll send an error message with a status code of 403 Forbidden.

Creating an Auth Service

To consume the users logic, we’ll create an auth service that will talk to the Users/SignIn API endpoint. We’ll create a file called AuthService.js, where we’ll define a function that takes in a username, password, and callback function as parameters.

Handling Errors and Success

We’ll handle errors by sending a second parameter to the callback function, passing the error object as the first one. If the error parameter is true, we’ll set an error state with the received message and stop proceeding. If not, we’ll check the status code to ensure it’s 200 OK.

Generating and Sending JWT from the Server

Currently, our sign-in API response only sends out HTTP 200. We’ll update this to send a success message along with a JWT generated on the server. We’ll create a JWT based on our default headers and claims, and send it to the client.

Updating Client-Side Logic

After updating the server-side code, we’ll update the client-side logic to handle the JWT response. We’ll decode the JWT and store it in the state, and also persist the login after refresh by storing the JWT in localStorage.

Bug Fixes and Comments

We’ll also fix some mistakes we’ve missed during development, such as clearing error messages during successful events and after signing out.

Deploying the Complete Code

Finally, we’ll deploy our complete code using React’s production build and Heroku. We’ll create a production build of our app, and then deploy it to Heroku using the command git push heroku master.

Conclusion

That’s it! We’ve now completed our series on building a full-stack MERN app using JWT authentication. We hope you’ve found this journey informative and interesting. Check out the complete code on GitHub and let us know your thoughts.

Leave a Reply

Your email address will not be published. Required fields are marked *