Skip to content

Instantly share code, notes, and snippets.

@bytrangle
Last active October 18, 2022 19:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bytrangle/98a0add2e1c65247df436bfa5c272932 to your computer and use it in GitHub Desktop.
Save bytrangle/98a0add2e1c65247df436bfa5c272932 to your computer and use it in GitHub Desktop.
Generate base64-encoded bearer token in Node.js
// import https module for making API calls
const https = require('https')
// import querystringify to construct a query from an object
const qs = require('querystringify')
const consumerApiKey = YOUR_CONSUMER_API_KEY
const apiSecretKey = YOUR_API_SECRET_KEY
const plainCredential = `${consumerApiKey}:${apiSecretKey}`
const bearerToken = Buffer.from(plainCredential).toString('base64')
// Example API request
const options = {
hostname: 'api.twitter.com',
port: 443,
method: 'POST',
path: '/oauth2/token?grant_type=client_credentials',
headers: {
'Authorization': 'Basic ' + bearerToken,
},
}
const promise = new Promise((resolve, reject) =>
https.request(options, res => {
let data = ''
res.on('data', chunk => data += chunk)
res.on('end', () => {
const auth = JSON.parse(data)
if(auth.token_type !== 'bearer')
return reject(new Error('Twitter auth failed.'))
const accessToken = auth.access_token
return resolve(accessToken)
})
}).end()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment