Building A FullStack Website With MERN #5 | Backend Authentication With JWT

in OCD4 years ago

Building A FullStack Website.png

Dear Hivers,

After taking a short break from this project, I'm back and the project is getting really close to completion now.

This is the fourth post in this series and as usual the links for the previous posts are given at the end of the post. Check out the introduction post for a better understanding of what I am trying to do here.


The Checklist

  • Set up the backend with NodeJs and Express ✔
  • Set up the database with MongoDB Atlas ✔
  • Set up the frontend with React and Reactstrap ✔
  • Implement Redux for state management ✔
  • Connect the backend and frontend ✔
  • Deploy the website online ✔
  • Backend auth with JWT ✔ ★
  • React and Redux auth state
  • Set up registration and login features

Only 2 more steps left! Yay!!


JWT And Authentication

What even is JWT?

According to jwt.io --

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

It works in a similar manner to site cookies.

When we login to a website, it generates an encoded JWT token which is then sent to the server and the server verifies whether the token belongs to the correct user. If it does, only then is the user allowed to access the data.


Adding More Routes

In order for a user to login or register, we need an api post route to send the form data of the user to our database.

For that, I created another route /api/users where we will perform the registration and /api/auth for the authentication.

The user will have 3 fields: name, email and password which will be encrypted using bcryptjs before storing in the database.

The schema for the user looks like this --

const UserSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true,
        unique: true
    },
    password:{
        type: String,
        required: true
    },
    register_date:{
        type: Date,
        default: Date.now
    }
})

The register_date field is automatically filled by javascript.

There are also a bunch of other changes which you can find on this commit on my github repo.


Conclusion

The backend is all done and now I need to create the login and registration components with react. I am dreading this step because I will have to work with redux again which is a huge pain in the ass.

Hopefully, I won't run into as much problems this time along.


My Portfolio: https://rahul-thapa.github.io

The rest of the posts in this series: