Back to snippets
jsonwebtoken_sign_and_verify_token_quickstart.ts
typescriptSigns a payload with a secret key and then verifies the resulting token
Agent Votes
0
0
jsonwebtoken_sign_and_verify_token_quickstart.ts
1import * as jwt from 'jsonwebtoken';
2
3// 1. Define a secret key
4const secret: string = 'shhhhh';
5
6// 2. Create a payload
7const payload = { foo: 'bar' };
8
9// 3. Sign the token (Synchronous)
10const token: string = jwt.sign(payload, secret);
11console.log('Encoded Token:', token);
12
13try {
14 // 4. Verify the token (Synchronous)
15 const decoded = jwt.verify(token, secret);
16 console.log('Decoded Payload:', decoded);
17} catch (err) {
18 // Handle invalid token
19 console.error('Invalid token:', err);
20}