NodeJS WebHook Question

I’m creating a NodeJS WebHook subscriber, and fronted a problem.

app.get("/twitch/subscribe", (req, res) => {
	const query = req.query.id
	if (query == null) {
		res.send("param missing. expecting 'id' param")
		return
	}
	request({
		uri: `https://api.twitch.tv/kraken/users?login=${query}`,
		method: "GET",
		headers: {
			"Accept": "application/vnd.twitchtv.v5+json",
			"Client-ID": "**hidden**"
		}
	}, function (err, result, body) {
		if (!err && result.statusCode === 200) {
			console.log(body)
			const json = JSON.parse(body)
			const count = Number(json._total)
			if (count === 0) {
				res.send(`User ${query} not found`)
				res.status(400).end()
			} else if (count > 1) {
				res.send(`Multiple user ${query} found`)
				res.status(400).end()
			} else {
				const id = json.users[0]._id
				request({
					uri: "https://api.twitch.tv/helix/webhooks/hub",
					method: "POST",
					headers: {
						"Accept": "application/vnd.twitchtv.v5+json",
						"Authorization": "Bearer **hidden**",
						"Client-ID": "**hidden**"
					},
					json: {
						"hub.callback": "http://**hidden**/twitch/live",
						"hub.lease_seconds": "864000",
						"hub.mode": "subscribe",
						"hub.topic": `https://api.twitch.tv/helix/streams?user_id=${id}`
					}
				}, function (error, result, body) {
					if (!err && result.statusCode === 202) {
						res.send(`Successfully registered to ${query} / ${id} for 10 days.`)
						res.status(200).end()
					} else {
						console.error(err)
						console.error(result.statusCode)
						console.error(body)
						res.send("Subscription error.")
						res.status(400).end()
					}
				})
			}
		} else {
			console.error(err)
			res.send("ID Request error.")
			res.status(400).end()
		}
	})
})

This is my code for subscription, and

app.get("/twitch/live", (req, res) => {
	const body = JSON.parse(res.body).data
	console.log(body)
	if (Object.keys(body).length > 0) {
		console.log("Stream Received")
	}
	console.log(req.query)
	res.send(req.query.hub_challenge)
	res.status(200).end()
})

app.post("/twitch/live", (req, res) => {
	const body = JSON.parse(res.body).data
	console.log(body)
	if (Object.keys(body).length > 0) {
		console.log("Stream Received")
	}
	console.log(req.query)
	res.send(req.query.hub_challenge)
	res.status(200).end()
})

This is my code for listening to webhook (not sure whether webhook is a post or a get)

When subscribing, i get 202, which i guess means successfully subscribed.
However, no single request was received (tested with my twitch id)

can anyone find a reason i can’t get a webhook?


EDIT
Got an error.
Line 74 is const body = JSON.parse(res.body).data
Maybe twitch is sending data after some delay?

SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
at W:\Servers\Webhook\index.js:74:20
at Layer.handle [as handle_request] (W:\Servers\Webhook\node_modules\express\lib\router\layer.js:95:5)
at next (W:\Servers\Webhook\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (W:\Servers\Webhook\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (W:\Servers\Webhook\node_modules\express\lib\router\layer.js:95:5)
at W:\Servers\Webhook\node_modules\express\lib\router\index.js:281:22
at Function.process_params (W:\Servers\Webhook\node_modules\express\lib\router\index.js:335:12)
at next (W:\Servers\Webhook\node_modules\express\lib\router\index.js:275:10)
at jsonParser (W:\Servers\Webhook\node_modules\body-parser\lib\types\json.js:110:7)

You’re parsing the response, rather than the request that Twitch is sending to you. The unexpected token u error is because the response body is undefined.

Also, in your webhook subscription request I noticed you have "Accept": "application/vnd.twitchtv.v5+json", this can be removed, only Kraken endpoints require you to specify a verison and this header does nothing in Helix.

oh… that was the problem…
the other problem is that twitch is not sending, or sending webhook too late (around 30 min after live?)
is it normal to be so?

1 to 5 minutes is normal for a stream going live/offline, which is to be expected due to caching and preventing a stream that has momentary outages from spamming webhook notifications.

30 minutes is not normal, but could be related to the major issues Twitch was having about 12 hours ago.

1 Like

Thanks. helped me a lot.
I will try it now again.
Thank you so much! :heart:

You may also be interested in this nodeJS example

https://github.com/BarryCarlyon/twitch_misc/tree/master/webhooks/handlers/js

Also request is deprecated, so you should consider a new library!

Thanks for the example!
Actually, this is my first time coding with node js (i am a jvm user)
I could not find a better library to replace request
Thank you so much @BarryCarlyon @Dist

Request lists many on it’s github

Most of us have gone to one of

  • got,
  • axios,
  • node-fetch

I believe

thanks! i’ll try to update my project!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.