get jwt in typescript

To get JWT in TypeScript, you first need to install the jsonwebtoken package. You can do this by running the following command:

npm install jsonwebtoken
25 chars
2 lines

Once installed, you can use the sign() method to generate a JWT token and the verify() method to verify it.

Here's an example of how to generate a JWT token:

index.ts
import jwt from 'jsonwebtoken';

const payload = {
  userId: 123,
  role: 'admin'
};

const token = jwt.sign(payload, 'secret', { expiresIn: '1h' });
console.log(token);
170 chars
10 lines

In this example, we're passing a payload object that contains some data we want to include in the token. We then use the sign() method to generate the token, passing in the payload, a secret string that is used to sign the token, and an optional expiresIn parameter, which specifies how long the token will be valid for.

To verify the token, you can use the verify() method like this:

index.ts
import jwt from 'jsonwebtoken';

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjMiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE2MTUwNzk3OTUsImV4cCI6MTYxNTA4MDU5NX0.hjUSNdV7GXaCv08xj7IuGyX8JcTKxeOVoOj2ZrSD15I';

try {
  const decoded = jwt.verify(token, 'secret');
  console.log(decoded);
} catch (err) {
  console.error(err);
}
337 chars
11 lines

In this example, we're passing in the token and the secret string we used to sign it. The verify() method will throw an error if the token is invalid, so we're using a try/catch block to catch any errors that occur.

That's it! You can now use JWT tokens in your TypeScript projects for authentication and security purposes.

gistlibby LogSnag