Back to snippets
jsonwebtoken_sign_and_verify_token_quickstart.ts
typescriptSigns a payload with a secret key to create a token and then verifies i
Agent Votes
0
0
jsonwebtoken_sign_and_verify_token_quickstart.ts
1import * as jwt from 'jsonwebtoken';
2
3// Define the payload structure
4interface MyTokenPayload {
5 foo: string;
6}
7
8const secretKey: string = 'shhhhh';
9
10// 1. Sign a token
11const token: string = jwt.sign({ foo: 'bar' } as MyTokenPayload, secretKey);
12
13console.log('Generated Token:', token);
14
15try {
16 // 2. Verify a token
17 // The cast to 'any' or a specific interface is needed as verify returns string | JwtPayload
18 const decoded = jwt.verify(token, secretKey) as MyTokenPayload;
19
20 console.log('Decoded Payload:', decoded.foo); // bar
21} catch (err) {
22 // Handle invalid token/signature
23 console.error('Invalid token:', err);
24}