Skip to content

Instantly share code, notes, and snippets.

@mfyz
Created October 25, 2019 13:53
Show Gist options
  • Save mfyz/72b3f7ba5ccca73a88044e7980c09a01 to your computer and use it in GitHub Desktop.
Save mfyz/72b3f7ba5ccca73a88044e7980c09a01 to your computer and use it in GitHub Desktop.
Single javascript file node/express/instagram authentication (oauth) and get user photos
const express = require('express')
const path = require('path')
const ig = require('instagram-node').instagram()
const cookieParser = require('cookie-parser')
// Set the config values below inline or from environment variables
const PORT = process.env.PORT || 8110
const IG_CLIENT_ID = process.env.IG_CLIENT_ID
const IG_CLIENT_SECRET = process.env.IG_CLIENT_SECRET
ig.use({
client_id: IG_CLIENT_ID,
client_secret: IG_CLIENT_SECRET
})
const igRedirecrUri = process.env.IG_REDIRECT_URI
const app = express()
app.use(express.static(path.join(__dirname, 'public')))
app.use(cookieParser())
app.get('/', (req, res) => {
res.send('<a href="/instagram/authorize">Login with Instagram</a>');
})
app.get('/instagram/authorize', (req, res) => {
res.redirect(ig.get_authorization_url(igRedirecrUri, {
scope: ['public_content', 'likes']
}))
})
app.get('/instagram/callback', (req, res) => {
ig.authorize_user(req.query.code, igRedirecrUri, (err, result) => {
if(err) return res.send(err)
// ideally, store token in db and create a
// browser session id to use the token from db
// but for quick demo, we'll use cookie store
// method below is not secure at all
res.cookie('igAccessToken', result.access_token)
res.redirect('/instagram/photos')
})
})
app.get('/instagram/photos', (req, res) => {
try {
// use ig token from db (that is linked to the browser session id)
// or for our demo version, get it from cookies
const accessToken = req.cookies.igAccessToken
ig.use({ access_token: accessToken })
const userId = accessToken.split('.')[0] // ig user id, like: 1633560409
ig.user_media_recent(userId, (err, result, pagination, remaining, limit) => {
if(err) return res.render('error')
// send photo array to a view or for our demo build html
// (list of ig photos) and return to the browser
let html = '';
result.map((photo) => {
html += '<a href="' + photo.link + '">' +
'<img src="' + photo.images.low_resolution.url + '"/></a><br/>'
})
res.send(html);
})
}
catch (e) {
res.render('error')
}
})
app.listen(PORT, () => console.log(`App listening on port ${PORT}!`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment