JSON Web Token (JWT)

JSON Web Token is a library for generating and verifying JSON Web Tokens (JWTs).

The JWT module is available via the following require() statement in PubNub Functions:

1const {sign, decode, verify} = require('jwt');

Exposed methods

Use these methods in your Function code:

  • decode — Extract the payload and, optionally, the header from a token without verifying its signature.
  • verify — Verify a token with a secret or public key and validate expected claims.
  • sign — Create and sign a token from a payload and a secret or private key.

Examples

1const jwt = require('jwt');
2
3// Example token (this should be a valid JWT)
4const token = 'your.jwt.token.here';
5
6const decoded = jwt.decode(token, { complete: true });
7console.log('Decoded Token:', decoded);

The decode method returns the token’s payload, and if { complete: true } is set, it returns an object containing both the payload and the header.

With { complete: true }:

Decoded Token: {
header: { alg: 'HS256', typ: 'JWT' },
payload: { userId: '123456', username: 'johndoe', iat: 1616239022, exp: 1616242622 },
signature: 'h04J3jUOeGXRHgZzg28pzF5omFxCeK2FlhEXbPZnQ'
}

Without { complete: true }:

Decoded Token: { userId: '123456', username: 'johndoe', iat: 1616239022, exp: 1616242622 }
Functions support

Functions provides a rich set of tools. For help with situations not covered here, contact PubNub Support.

Last updated on