JWT Authentication (Node Js)

Parth Padhiar
3 min readNov 28, 2020

jwt authentication
signup, login, logout APIs

JWT : JSON Web Token

JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

Authorization is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single sign-on is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

Install

$ npm install jsonwebtoken express body-parser mongoose bcrypt cookie-parser
  1. install all node modules above shown.

2. create folders and files shown below.

1. Structure

3. now open app.js file and write below code. that runs on PORT 3000.

run above code for that install nodemon so you don’t have to write npm app.js, just save code and server will restart automatically.

$ npm i nodemon -g

  • -g for global so you don't have to install every time.
  • and change “main”: “app.js”

4. now in user.model.js file write below code in which we create schema and models and export them

5. Create config.js file in we write code that we use in our project globally so we don’t have to define it every single time.

6. now in user.model.js file we write code for register, compare password, generate token, find by token, delete token

7. Create auth.js file.

8. now in app.js file require mongoose, body-parser, cookie-parser

All files.

  • app.js
  • config.js file is save as last one.
  • user.model.js
  • auth.js is also same.

Output

1. register
2. login
2.1 login token
3. User profile
4. Log-Out

full code on GitHub: https://github.com/parthpadhiar/node-jwt-auth

--

--