Register & login with JWT (Json web token) in express

Deepak Tailor Image
Deepak Tailor - Dec 02 2021
Register & login with JWT (Json web token) in express

How to register user in nodejs. How to generate json web token when registered. And how to login the user.

1. Install json web token in express (npm install jsonwebtoken)

2. Import json web token in route file

3. Create register or login route

import jwt from 'jsonwebtoken';
user register request

1. Insert student data into database

2. Create token with jwt

3. Return token to client

url : http://localhost:3000/register

{
    "first_name": "Deepak",
    "last_name": "Tailor",
    "mobile_no": "7742307462",
    "email_id": "deepaktailor@gmail.com",
    "password": "123456"
}
router.post('/register', async (req, res) => {
    const data = req.body;

    try {
        const result = await student.create( data );
        const id = result._id;

        const jwt_data = jwt.sign({user_id : id}, 'JWT_SECRET', { expiresIn : '1h'});
        return res.json({data : jwt_data });

    } catch (error) {
        return res.json({data : error.message});
    }
});
{
    "data": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiNjFhNGJkMzA5MmI1MzdlYmRhYmI0OTU5IiwiaWF0IjoxNjM4MTg2Mjg4LCJleHAiOjE2MzgxODk4ODh9.z0RXiMmTPNm3v3oCkjp0GRCECLB61gZbKDpnr1PwDsQ"
}
User login request

1. find student data into database

2. if user is find then Create token with jwt else send error

3. Return token to client

url : http://localhost:3000/login

{
    "email_id": "deepaktailor@gmail.com",
    "password": "123456"
}
router.post('/login', async (req, res) => {
    const email = req.body.email_id;

    try {
        const result = await student.find({ email_id : email });

        if(result != ""){
            const id = result._id;
            
            const jwt_data = jwt.sign({user_id : id}, 'JWT_SECRET', {expiresIn: '1h'});
            return res.json({data : jwt_data });
        }else{
            return res.json({data : "try again ! email id not found"});
        }

    } catch (error) {
        return res.json({data : error.message});
    }
});
{
    "data": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiNjFhNGJkOTA5MmI1MzdlYmRhYmI0OTViIiwiaWF0IjoxNjM4MTg2Mzg0LCJleHAiOjE2MzgxODk5ODR9.EHRXuxclK3mtybUd3b4R48dhQAb0ca6m5L_WWrNxgVM"
}
Deepak Tailor Image
Deepak Tailor

My name is Deepak tailor as a fullstack developer. I have been in the IT industry (PHP, Nodejs, flutter) for the last 5 years. For professional and customize web development & app development, you can send inquiry on our email.
----
You can contact him at deepaktailor10@yahoo.in


Do you want to make website?

Message on WhatsApp, Plan your business idea with your website.

+91 7742307462