Skip to content

Instantly share code, notes, and snippets.

@jpeckham
Last active July 25, 2023 06:55
Show Gist options
  • Save jpeckham/6555a410c4f29731b6bd41957dc196ad to your computer and use it in GitHub Desktop.
Save jpeckham/6555a410c4f29731b6bd41957dc196ad to your computer and use it in GitHub Desktop.
login to the reddit api and use a bearer token
/*
from quickstart https://github.com/reddit-archive/reddit/wiki/OAuth2-Quick-Start-Example
*/
const axios = require('axios')
const qs = require('querystring');
const main = async function () {
/*
all four of these veriables below should be kept secure
*/
// client id and secret come from making a 'script' app at this site https://www.reddit.com/prefs/apps
const clientId = process.env.REDDITAPI
const clientSecret = process.env.REDDITSECRET
// this is the developers reddit uid and pwd. as if they were logging into reddit site.
const uid = process.env.REDDITUID
const pwd = process.env.REDDITPWD
let resp = await axios
.post(
'https://www.reddit.com/api/v1/access_token',
qs.stringify({
grant_type: 'password',
username: uid,
password: pwd
}),
{
auth: { username: clientId, password: clientSecret }
})
.catch(function (err) { throw err })
console.log('response.data:')
console.log(resp.data)
let bearerToken = resp.data.access_token;
//note when using bearer tokens you then go to oauth.reddit.com
resp = await axios
.get('https://oauth.reddit.com/api/v1/me',
{
headers: {
Authorization: 'bearer '+ bearerToken
}
})
.catch(function (err) { throw err })
console.log('response.data:')
console.log(resp.data)
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment