jwt
The jwt built-in module is available only inside a PubNub Function. It creates, decodes, and verifies JSON Web Tokens (JWTs).
1const { sign, decode, verify } = require('jwt');
sign
sign(payload, secretOrPrivateKey, options?)
* required
| Parameter | Description |
|---|---|
payload *Type: Object | Claims to encode in the token. |
secretOrPrivateKey *Type: String | Secret or private key used to sign the token. |
optionsType: Object | Signing options, for example expiresIn. |
Returns: the signed JWT, as a string.
1const jwt = require('jwt');
2const payload = { userId: '123456', username: 'johndoe' };
3const secretKey = 'your-256-bit-secret';
4const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
decode
decode(token, {complete}?)
* required
| Parameter | Description |
|---|---|
token *Type: String | Token to decode. |
completeType: Boolean | If true, returns the header and signature along with the payload. |
Returns: the token's payload. If complete: true, returns {header, payload, signature} instead. decode() does not verify the signature.
1const jwt = require('jwt');
2const decoded = jwt.decode(token, { complete: true });
3// { header: { alg: 'HS256', typ: 'JWT' }, payload: { userId: '123456', ... }, signature: '...' }
verify
verify(token, secretOrPublicKey, options?, callback?)
* required
| Parameter | Description |
|---|---|
token *Type: String | Token to verify. |
secretOrPublicKey *Type: String | Secret or public key used to verify the signature. |
optionsType: Object | Verification options, for example expected claims. |
callbackType: Function | Node-style callback. |
Returns: the decoded payload if verification succeeds. Throws if verification fails (tampering, expiration, or wrong key).
1const jwt = require('jwt');
2try {
3 const decoded = jwt.verify(token, secretKey);
4 console.log('Decoded Payload:', decoded);
5} catch (err) {
6 console.error('Token verification failed:', err.message);
7}
Related reference
- Modules and libraries. Every built-in module available inside a Function.