Posted in Javascript

Simple JWT Authentication with NodeJS Example

Simple JWT Authentication with NodeJS Example Posted on June 22, 2019Leave a comment

To read this post, you have to be familiar with basic Express, Mongoose and solid Javascript background.

Libraries I’ve used in this example:

Project structure:

  • index.js – main file
  • user-model.js
  • user-routes.js
  • templates
    • index.hbs
    • login.hbs
  • assets
    • script.js

Let’s get started!

Step 1: Create user-model.js file

to create test user, just use this code on anywhere of your project, after created users, please commented out these lines:

Step 2: Create user-routes.js

Notice: I don’t check validation of inputs, we can do it later because this is just a basic example to understanding how to authenticate user with JWT in NodeJS app.

Step 3: Create login.hbs (login template)

Step 4: Create script.js to send login data to server

Notice: you must use async await to get response data correctly.

Step 5: Create index.js

Step 6: Create index.hbs

All done! to get project’s source code, please visit my github

Happy coding!

Leave a Reply

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