protected-mid
v1.0.5
Published
This npm package provides middleware for protecting routes in a backend application using JSON Web Tokens (JWT). It verifies the presence and validity of a JWT token from the client's cookies, retrieves the user ID, and fetches user details from a specifi
Downloads
16
Readme
Npm-Package-Protected-routes
This npm package provides middleware for protecting routes in a backend application using JSON Web Tokens (JWT). It verifies the presence and validity of a JWT token from the client's cookies, retrieves the user ID, and fetches user details from a specified user model. If successful, it attaches the user object to the request (req.user
) for subsequent route handling. Handles various error scenarios like missing or invalid tokens, unauthorized access, and internal server errors.
Installation
Install the package via npm:
npm install protected-mid
Usage
import ProtectedApp from "protected-mid"
import userModel from "../models/userModel.js"
Setting Up
Define options for ProtectedApp:
const options ={
secret:process.env.JWT, jwt secret key
tokenName:'token', name of token which you stored in cookies
getUserId:(decodedToken)=>decodedToken.userId, pass id or userId which you used to generate jwt token
userModel:userModel pass userModel here to get login user }
Using Middleware
Apply ProtectedApp middleware to protect your routes:
// Example route protected by the middleware
router.get('/getuser', ProtectedApp(options), controller )