How to use jwt jsonwebtoken package in node js using npm
Using the jwt jsonwebtoken package in Node.js
To use the jsonwebtoken
package in Node.js, you can follow these steps:
Install the
jsonwebtoken
package using npm by running the following command in your terminal:npm install jsonwebtoken
Import the
jsonwebtoken
module in your Node.js file using therequire
function:javascript const jwt = require('jsonwebtoken');
Generate a new JWT token using the
jwt.sign
method. This method takes two parameters: the payload and the secret key. The payload is an object that contains the data you want to include in the token, and the secret key is a string used to sign the token and verify its authenticity. Here's an example:javascript const payload = { userId: 123 }; const secretKey = 'your-secret-key'; const token = jwt.sign(payload, secretKey);
You can now use the generated token for authentication or authorization purposes. You can include the token in the headers of your HTTP requests or store it in a secure location, depending on your application's requirements.
To verify the authenticity of a token, you can use the
jwt.verify
method. This method takes three parameters: the token, the secret key, and an optional callback function. Here's an example:javascript const token = 'your-token'; const secretKey = 'your-secret-key'; jwt.verify(token, secretKey, (err, decoded) => { if (err) { // Token is invalid or expired console.error(err); } else { // Token is valid console.log(decoded); } });
The decoded
object contains the decoded payload of the token.
Please note that the secret key should be kept secure and should not be shared publicly. It is used to sign and verify the token, ensuring its authenticity.