Displaying an Instagram feed with Gatsby [Part 1]

Published May 02, 2019

Revised for 2020! Instagram deprecated their old API access method, so I've re-written this tutorial to reflect the new method for gaining API access.

Introduction

In this three-part tutorial, I'll show you how to build a gallery of Instagram posts in Gatsby.

Pre-requisites

For Part 1 of the tutorial, you'll need:

1) Get an Instagram access token

In order to get our posts into GraphQL, we'll use the gatsby-source-instagram-all plugin, which requires an access token from Facebook. This process is a bit lengthy – it may take about 20-30 minutes if you're moving through it for the first time.

Create a new app

  1. Go to the Facebook Developer Portal and log into your Facebook account.

  2. Go to the My Apps page and select the Create App button.

  3. A dialog box will open asking you to categorize your app. Select Something Else in the list of options, and then select Continue.

Partial screenshot from "What do you need your app to do?" questionnaire with "Something Else" option selected

  1. The next step in the dialog box will ask you to fill in or verify some details about the app you're creating:
  1. Select the Create App button (and verify that you're not a robot).

Add a platform

The dialog should close, and you'll need to specify a platform for your app before we can move on.

  1. In the left column, select Settings. After the menu expands, select Basic.

  2. You'll be presented with a page containing your app's details. Navigate all the way down to the bottom of the page and locate the faint gray box with + Add Platform inside of it. Select the box.

Partial screenshot from App Basic Settings page with "Add Platform" button in focus

  1. A dialog box will open with a list of platforms. Select Website.

  2. The dialog will close, and a new block will appear above the "Add Platform" block with a field to enter a Site URL. Enter the base URL to the site where the gallery will appear - including the protocol (https:// or http://). Using my site as an example, I'd enter https://www.desiraebeberniss.com.

Partial screenshot from App Basic Settings with Site URL field filled in with https://www.desiraebeberniss.com

  1. When you're done, select Save Changes.

Select a product

  1. In the left column, select Products +. In the list that appears, locate Instagram Basic Display and select the Set Up button.

  2. On the page that loads, you should see "Basic Display" at the top. Select the Create New App button at the bottom.

  3. A dialog box will open to confirm that you want to create an app ID that's specific to Instagram. It will pre-populate the Display Name field with the name you used when you created the Facebook app. If it all looks good, select the Create App button.

  4. You should now see a page that shows your Instagram App ID, an obfuscated Instagram App Secret, and a few other fields. You'll need to fill out three fields with your site's URL - go ahead and use the same base URL you used for Site URL earlier:

Partial screenshot from Instagram Basic Display settings with Redirect, Callback, and Request URL fields filled in with https://www.desiraebeberniss.com

  1. Select the Save Changes button at the bottom.

Send a tester invite

  1. Navigate down to the "User Token Generator" block and select the Add or Remove Instagram Testers button.

Partial screenshot from Instagram Basic Display settings with User Token Generator block in focus

  1. On the page that loads, you should see your account listed in the "Administrators" block. Navigate down to the "Instagram Testers" block towards the bottom and select the Add Instagram Testers button.

  2. In the dialog box that opens, enter the Instagram username for the account you're connecting to. Once you've located the account, select the Submit button. The Instagram user you selected should now appear as "Pending" in the list of testers.

Ok! We're almost there 🙌. Leave this browser tab open as we go through the next step.

Accept the tester invite

  1. Go to Instagram in a new browser tab, and log in as the account you used in the last step.

  2. Navigate to the profile settings page by selecting the user avatar in the upper right, and selecting Settings from the dropdown menu.

  3. In the left column, locate and select the Apps and Websites menu option.

  4. On the page that loads, select the Tester Invites tab. You should see the invite that's named after the Facebook app you created. Select the Accept button next to the invite.

Partial screenshot from Apps and Websites screen in Instagram's Profile Settings that shows an invite to become an Instagram Tester

This Instagram account is now an authorized user for this app, which will allow us to generate an access token for this user!

Generate the Facebook token

Let's return to the Facebook Developer Portal tab.

  1. In the left column, select Instagram Basic Display. In the expanded menu, select Basic Display.

  2. Navigate down the page to the "User Token Generator" section. You should see the authorized Instagram test account listed there. Select the Generate Token button next to the user.

Partial screenshot from Instagram Basic Display Settings with a test user listed

  1. Your browser will then open a popup window asking you to log into Instagram. Log in as the Instagram user we've been using throughout this process. You'll be prompted to authorize permissions; select the Accept button.

  2. Keep the popup window open! You should see some disclaimer text and a checkbox that says "I Understand" - go ahead and select it.

Save the token

You should now see the unobfuscated Access Token that we've jumped through so many dialog windows, logins, and forms to get to 👏

Go ahead and copy the token to your clipboard now, and then paste it and save it in a secure place.

Important: While the token will only let you read data from Instagram's API for this one account, you probably don't want it to be easily discoverable, especially in public repos on GitHub. I'll cover how to handle the access token through Netlify's environment variables towards the end of the next step.

2) Add gatsby-source-instagram-all & gatsby-image

We're going to add two plugins to our Gatsby site to grab and render our Instagram posts. The gatsby-source-instagram-all plugin enables us to use the Instagram API as a data source for GraphQL, and the gatsby-image plugin provides a React component that we'll use to render optimized versions of our Instagram photos.

I'm using yarn as the package manager for my site; use whatever package manager you have set up to install both plugins:

yarn add gatsby-image gatsby-source-instagram-all

Let's configure gatsby-source-instagram-all first. Add this configuration to your gatsby-config.js as a new object inside the plugins: [...] array:

{
  resolve: `gatsby-source-instagram-all`,
  options: {
    access_token: "YOUR_ACCESS_TOKEN"
  }
}

You can paste your token between the quotes for access_token, or, you can follow these optional steps that add a level of obfuscation for your token by turning it into an environment variable, so that you're not directly committing it to your code repo.

Optional: Set the token using an environment variable in Netlify

  1. In the Netlify dashboard for your site, select Site settings.

  2. In the left column, select Build & deploy. Navigate down the page to the "Environment" section and locate the "Environment Variables" block. Select the Edit Variables button; an inline form should appear.

  3. For the key, use GATSBY_INSTAGRAM. For the value, paste in the token. Select the Save button.

  4. If you don't have any existing environment variables in your Gatsby project, create a new file named .env.development.

  5. Open the file and add the following (replacing your_token_here with your own token).

GATSBY_INSTAGRAM=your_token_here
  1. Save the file, and ensure that you exclude it from commits to your code repo. I'm using Git via GitHub, so this line in .gitignore prevents this file from being committed:
.env*
  1. At the very top of your gatsby.config.js file, add the following to make your environment variable file available to Gatsby. If Gatsby is already running, you'll need to restart your project for this to take effect.
require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
});

Now you can use the environment variable in your code, instead of the actual token. While still in gatsby.config.js, update the gatsby-instagram-all-config to look like this:

{
  resolve: `gatsby-source-instagram-all`,
  options: {
    access_token: process.env.GATSBY_INSTAGRAM
  }
}

You can then restart Gatsby and move onto the next step.

3) Creating the Instagram component

Determine where you're going to place your Instagram component. For my site, I'm going to create a new folder named "Instagram" within my /components folder.

My Gatsby starter uses default exports, so first I'll create an index.js file.

// index.js
export { default } from './Instagram';

Next, I'll create the basic template for the display widget. I've adapted some of the JSX and GraphQL code from the demo repo provided by the creator of gatsby-source-instagram-all.

// Instagram.js
import React from 'react';
import { graphql, StaticQuery } from 'gatsby';
import Image from 'gatsby-image';

const Instagram = () => (
  <StaticQuery
    query={graphql`
      query InstagramPosts {
        allInstagramContent(limit: 12) {
          edges {
            node {
              link
              localImage {
                childImageSharp {
                  fluid(maxHeight: 500, maxWidth: 500 quality: 50) {
                    ...GatsbyImageSharpFluid_withWebp_tracedSVG
                  }
                }
              }
              images {
                standard_resolution {
                  width
                  height
                  url
                }
                low_resolution {
                  url
                }
              }
            }
          }
        }
      }
    `}
    render={(data) => (
      <div>
        {
          data.allInstagramContent.edges.map((item, i) => (
            item.node.localImage ? (
              <div key={i}>
                <Image
                  fluid={item.node.localImage.childImageSharp.fluid}
                />
              </div>
            ) : (<div></div>)
          ))
        }
      </div>
    )}
  />
);

export default Instagram;

I can then import and add the component to my existing page template. When I reload a page, I can see 12 of my latest Instagram posts being loaded 🥳.

Hopefully you can see posts being loaded into your page too! If you don't, be sure to check your Terminal/console to see if there are any errors coming from the GraphQL query or gatsby-source-instagram-all.


Related posts