JSON WEB TOKEN to encrypt Your data in NODE JS 2022 (2024)

Applications used this time:

  • vscode
  • postman
  • XAMPP (for windows) / LAMPP (for linux)
  • node js / npm

before starting to program we have to install the jsonwebtoken package by writing the code in the terminal like this

npm i jsonwebtoken

in the .env file create a variable named SECRETE_TOKEN and fill it with your secret token as below:

# for JSON WEB TOKEN
SECRET_TOKEN=ThISIsSeCrEtETOkEN

3. Create New Token on Controller

previously import the jsonwebtoken package that was installed earlier and call the .env file like this

const jwt = require("jsonwebtoken");
require("dotenv").config();

in the userController we create a variable with the result of data encryption to which we will add the token we created and the expiration period

const token = await jwt.sign(
{
username: req.body.username,
password: req.body.username,
},
process.env.SECRET_TOKEN,
{
expiresIn: "24h",
}
);

4. Replace Token in Query Database

After creating the token variable, we replace the token in the database with req.body.username+req.body.password into the token variable that we created earlier, it looks like this:

Create New User

await model.user.create({
username: req.body.username,
password: req.body.password,
token: token,
})
.then((result) => {
res.status(201).json({
message: "user successful created",
data: {
username: req.body.username,
password: req.body.password,
token: token,
},
});
});

Update User

await model.user.update(
{
username: req.body.username,
password: req.body.password,
token: token,
},
{ where: { id: req.body.id } }
);
res.status(200).json({
message: "update successful",
data: {
id: req.body.id,
username: req.body.username,
password: req.body.password,
token: token,
},
});

5. Test On Postman

Create New User

JSON WEB TOKEN to encrypt Your data in NODE JS 2022 (1)

Update User

JSON WEB TOKEN to encrypt Your data in NODE JS 2022 (2)

after creating a token with JWT in this article it will be easier for us to create authentication with middleware which we will discuss in the next article

See You ~~~

JSON WEB TOKEN to encrypt Your data in NODE JS 2022 (2024)
Top Articles
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated:

Views: 5835

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.