JSON Web Token (JWT)

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

The jsonwebtoken module is made available with the following require() statement:

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

Exposed methods

You can use these methods from the library directly in your Function's code:

  • decode to extract and return the payload and optionally the header from a token without verifying its signature or authenticity.
  • verify to check the validity of a given token against a secret key, ensuring it hasn’t been altered and meets expected conditions.
  • sign to create and sign a new JWT with the provided payload and secret key.

Examples

const jwt = require('jsonwebtoken');

// Example token (this should be a valid JWT)
const token = 'your.jwt.token.here';

const decoded = jwt.decode(token, { complete: true });
console.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, and this documentation does not cover all of the potential situations you may encounter. If you need help with a situation not covered by the documentation, please contact PubNub Support

Last updated on