![]() |
VOOZH | about |
In this article, we will see how to create JWT tokens in Node.js. We will implement secure authentication in Node.js by creating and verifying JSON Web Tokens (JWTs) using libraries like `jsonwebtoken`.
Step 1: Firstly set up the NodeJs project. If you do not have NodeJs or NPM please refer to this article. Initiate NodeJs project with npm.
npm init -yStep 2: After initiating the project install some dependencies. Install express, and jsonwebtoken through npm
npm install express jsonwebtokenStep 3: Install nodemon as a dev-dependency.
npm install -d nodemonThe updated dependencies in package.json file will look like
"dependencies": {
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"nodemon": "^3.0.2",
}
Step 4: Add one more script in the package.json file. Open the package.json file and add one line below to the test script.
jwt.sign(
{data_obeject},
"secret_key",
{Options}
)
// Verify route
app.get('/auth', (req, res) => {
// Get token value to the json body
const token = req.body.token;
// If the token is present
if(token){
// Verify the token using jwt.verify method
const decode = jwt.verify(token, 'secret');
// Return response with decode data
res.json({
login: true,
data: decode
});
}else{
// Return response with error
res.json({
login: false,
data: 'error'
});
}
});
jwt.verify(token_value, 'secret_key');Example: Below is the complete code of the above step by step implementation
Step to test the routes: We will use Postman to test the API routes. Firstly test the login route. Open the postman and make a post request on the '/login' route with appropriate JSON data.
Output: Send a POST request to localhost at '/login' with login data, receive a JSON response with login status and token/object data, then use the token to authenticate a GET request to '/auth'. After validation, you will get the proper data object store in the token.