JSON Web Token (JWT) is a secure and stateless authentication method that allows users to authenticate using a signed token instead of traditional session-based authentication. This document provides a detailed overview of how JWT authentication works in an Express.js application.
- User Login: The client sends a login request with valid credentials (username and password).
- Token Generation: If authentication is successful, the server generates a JWT token, signs it with a secret key, and returns it to the client.
- Token Storage: The client stores the token in html-cookie
- Sending Requests: For each protected request, the client includes the JWT in the
Authorizationheader. - Token Verification: The server verifies the token using the secret key and grants access if it's valid.
- Accessing Protected Routes: The user can now access restricted endpoints until the token expires.
- make sure you have node and npm installed
git clone https://github.com/manoj-netizenn/jwt-authcd "project directory"npm installnpm install express jsonwebtoken ejs mongoose cookie-parser bcrypt- if any dependency goes missing run
npm i dependency-name -D- install Mongoose in your project:
npm install mongooseconst mongoose = require('mongoose');The basic MongoDB connection string format is:
const url="mongodb://localhost:27017/your_database"
mongoose.connect("url").then().catch()
//replace this with your local database string or connection string from mongodb accountnode server.jsor
npm run serverproject is now running on localhost:3000