JWT is a method or standard way of securely transferring or transmitting between two parties as a json token.
The compressed size of the tokens easily make it to be transmit and transfer through an URL (POST), or inside an HTTP header. The information is contained in a digitally signed using a Secret_key usually in an environment.
JWTs are using a secret or private key to sign in.
So, JWTs are mainly used for authentication. When a user login in to an application, the application then assigns and apportions JWT token to that user. Subsequent requests by the user will include the assigned JWT. This token tells the server what routes, services, and resources the user is allowed to access.
The JWT token is mainly for these followings:
It provides simple verification through a JSON Web Token
It is use an authentication service or outsource it
It provides more security and trustworthiness than cookies or sessions
So, let us dive to how to construct it with our application.
first, you need to create a server like this.
create a directory call jwtauth. you can call yours any name.
in it. when opened in the terminal, I preferred VSCode, initialise it, I’m using Express.js as a framework.
npm init -y
and then, you can now install the necessary packages e.g. express, jsonwebtoken, dotenv, etc.
npm install express dotenv jsonwebtoken
so, after the installation of the above.
let us create a folder that would housing JWT as a middleware.
and then, create a controller and route.
this is for the user to login and when successfully login in, it will generate token.
after you successfully constructed the login logic as you can see the user has 30mins for the jwt token to be expired.
Now, let us create the route file.
Let us try to login using Postman.
4 thoughts on “How to use JWT for Authentication in Node.Js”
I use JWT for auth as it have great and huge community.
For now, it’s still the best.
Thanks for sharing this!!
good stuff! Thanks for sharing.