Getting 401 Unauthorized Error on Send Pubsub Extension Message

I’m receiving this error message calling the API for Send Pubsub Extension Message:
error: ‘Unauthorized’,
status: 401,
message: ‘jwt token is required’

this is my code for creating a JWT token:

const makeJWT = function(targetChannelID)
{
    var secret = Buffer.from(process.env.TWITCH_EXT_SECRET, 'base64');
    const jwt_payload = {
        "exp": Math.floor(new Date().getTime() / 1000) + 60,
        "user_id": process.env.DEVELOPER_USER_ID,
        "role": "external",
        "channel_id": targetChannelID.toString(),
        "pubsub_perms": {
          "send": [
            "broadcast"
        ]
        }
      };
      return jwt.sign(jwt_payload, secret);
}

Is there a problem with this that I am receiving the 401 error?

The error indicates that your POST request to the API is missing the relevant headers for authorization.

Not that your JWT wasn’t constructed correctly.

So we need to debug your POST request initially

Example code: twitch_misc/extensions/chat/send_chat.js at main · BarryCarlyon/twitch_misc · GitHub I do a minimal JWT creation here.

The error you have is in the request you make (line 31 for me onwards) not the signing request (line 22->27 in my code)

This is my PubSub Request using axios:

async function sendPubsub(msgBody, targetChannelID)
{
    var pubsubEndpoint = "https://api.twitch.tv/helix/extensions/pubsub";
    const payload = {
        "target": ["broadcast"],
        "broadcaster_id": targetChannelID.toString(),
        "message": JSON.stringify(msgBody),
      };

      var token = makeJWT(targetChannelID);

      const options = 
      {
        headers:
        {
            "Authorization": BearerSubstring + token,
            "Client-Id": process.env.TWITCH_EXT_CLIENT_ID,
            "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
      }

      try {
        const response = await axios.post(pubsubEndpoint, options);
        
        console.log(response);
    } catch (err) {
        console.log(err);
    }

}

Ah derp pubsub not chat, doesn’t change the header construction however.

Reference example correction: twitch_misc/extensions/pubsub/node/send.js at main · BarryCarlyon/twitch_misc · GitHub

So

What is BearerSubstring set to?

It should be Bearer not Bearer

Ref: twitch_misc/extensions/pubsub/node/send.js at main · BarryCarlyon/twitch_misc · GitHub

So you would send

Bearer SIGHERE

Not

BearerSIGHERE

I switched the from axios to node-fetch and it finally worked. Thanks for the help!