jwt middle ware to verify a user

PHOTO EMBED

Sun Jul 17 2022 09:10:16 GMT+0000 (Coordinated Universal Time)

Saved by @gazifahad #javascript #nodejs #jwt #login

import jwt from 'jsonwebtoken'
const auth=async (req,res,next)=>{
    try {
       const token=req.headers.authorization.split(''[1]);
       const isCustomAuth=token.length<500;
       let decodedData;
       if(token && isCustomAuth){
               decodedData=jwt.verify(token,process.env.SECRET);
              req.userId=decodedData?.id;
       }
       else{
        decodedData=jwt.decode(token);
        req.userId=decodedData?.sub;
       }
       next();
    } catch (error) {
        console.log(error);
    }
}
content_copyCOPY

to verify a user for certain action we need to put this middle ware in the action code