Jsonwebtoken NPM Nodejs
JSON Web Token (JWT) is a standard for creating access tokens that are used to authenticate users and secure information. The jsonwebtoken npm package is a popular library for working with JWTs in Node.js. It provides a set of methods for creating, signing, and verifying JWTs.
To install the jsonwebtoken package, you can use the npm command-line tool by running the following command:
npm install jsonwebtokenThe jsonwebtoken npm package provides a set of methods for working with JSON Web Tokens (JWT) in Node.js. JWTs are a standard for creating access tokens that are used to authenticate users and secure information.
Get Barath Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
Here are some of the key features and methods provided by the jsonwebtoken package:
sign(payload, secret, options): This method is used to create and sign a JWT. Thepayloadparameter is an object that contains the information you want to include in the JWT. Thesecretparameter is a string that is used to sign the JWT and it is used to verify the JWT later. Theoptionsparameter is an object that can be used to set various options such asexpiresIn,algorithm, andheader.verify(token, secret, options): This method is used to verify a JWT. It takes thetoken(the JWT) and thesecret(the same secret that was used to sign the JWT) as arguments. If the token is valid and was signed with the correct secret, the method will return the payload of the JWT. If the token is invalid or has been tampered with, the method will throw an error.decode(token, options): This method is used to decode a JWT without verifying the signature. It takes thetokenas an argument and returns the payload.jwt.sign()andjwt.verify()support multiple algorithms like 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'none'.jwt.sign()andjwt.verify()also support options likeexpiresIn,notBefore,audience,issuer,subject,jwtid,noTimestamp,header,encoding
// create a JWT
const payload = { userId: 1 };
const secret = 'my-secret-key';
const options = { expiresIn: '1h' };
const token = jwt.sign(payload, secret, options);
console.log(token);// verify a JWT
const decoded = jwt.verify(token, secret);
console.log(decoded);
Here is an example of how you might implement JSON Web Tokens (JWT) in a Node.js application using the jsonwebtoken npm package:
- First, you will need to install the
jsonwebtokenpackage by running the following command in your terminal: - Next, in your server-side code, you can import the
jsonwebtokenpackage and use it to create and sign a JWT when a user logs in:
app.post('/login', (req, res) => {
// validate user credentials
// ... // create a JWT
const payload = { userId: 1 };
const secret = 'my-secret-key';
const options = { expiresIn: '1h' };
const token = jwt.sign(payload, secret, options); // send the JWT to the client
res.json({ token });
});
In this example, when a user logs in, the server will create a JWT with a payload of { userId: 1 }, signed with the secret key my-secret-key, and expires in 1 hour. The JWT is then sent to the client as a response to the login request.
- On the client-side, you can store the JWT in a cookie or local storage to keep the user logged in. On each subsequent request, you can include the JWT in the
Authorizationheader:
const token = localStorage.getItem('token');
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;- Finally, in your server-side code, you can use the
jsonwebtokenpackage to verify the JWT on each request:
app.use((req, res, next) => {
// get the token from the headers
const token = req.headers.authorization; // verify the token
try {
const decoded = jwt.verify(token, 'my-secret-key');
req.user = decoded;
next();
} catch (err) {
return res.status(401).json({ message: 'Unauthorized' });
}
});In this example, the server will extract the JWT from the Authorization header of each request and use the jsonwebtoken package to verify the JWT using the same secret key that was used to sign the JWT. If the JWT is valid, the server will set the req.user property to the payload of the JWT and call the next() function to proceed with the request. If the JWT is invalid, the server will return a 401 Unauthorized status code.
It’s important to keep in mind that JWT tokens should be signed using a private key and verified using a public key in production. Also, JWT tokens should be transmitted over HTTPS to prevent man-in-the-middle attacks.
This is a basic example of how you might use the jsonwebtoken package to implement JWT authentication in a Node.js application. Depending on the requirements of your application, you may need to customize this example to fit your needs.






