Add a live Instagram feed to Next.js

Show your latest Instagram posts in a Next.js App Router site with a server component and next/image. We handle Instagram authorisation and token refresh; Next.js renders the gallery, and the API key never reaches the browser.

Why doing it yourself breaks

  • Instagram Basic Display was shut down on 4 December 2024, so many Next.js tutorials and packages no longer work.
  • The Instagram API with Instagram Login needs a Business or Creator account, a Meta app and a long-lived token that lasts 60 days and must be refreshed. See our access token guide for the details.
  • media_url links point at Instagram's CDN and expire, so a statically generated page ends up with broken images.

Feedframer is a data API: connect your Instagram account once, and we refresh the token server-side, copy images and videos to our CDN and give you one URL. Every plan has unlimited API calls, no view metering, and REST JSON, GraphQL and RSS. Free covers a typical single small-business site: one account and its six latest posts, updated daily. Premium adds up to five accounts, up to 100 posts per request and hourly updates; see pricing.

1. Connect the Instagram account

Create a free account , connect an Instagram Business or Creator account, wait for the import to finish and copy its API key from the dashboard. The account owner must authorise the connection: typing a public username does not connect an arbitrary account. Personal Instagram accounts cannot be connected.

2. Keep the key in a server-only environment variable

Add this to .env.local and to your host's environment settings:

FEEDFRAMER_API_KEY=YOUR_API_KEY

Keep .env.local out of Git. Do not prefix the variable with NEXT_PUBLIC_: Next.js inlines those into the browser bundle. Without the prefix, process.env.FEEDFRAMER_API_KEY is only readable on the server.

3. Allow Feedframer images in next/image

We serve stored media from cdn.feedframer.com. If a file was not stored, mediaUrl falls back to Instagram's own CDN (scontent.cdninstagram.com). Allow both hosts, or next/image refuses to load them:

// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  images: {
    remotePatterns: [
      { protocol: 'https', hostname: 'cdn.feedframer.com' },
      { protocol: 'https', hostname: 'scontent.cdninstagram.com' },
    ],
  },
};

export default nextConfig;

Would rather not use next/image? A plain <img> with loading="lazy" works too and needs no config, though Next.js's ESLint preset will warn about it.

4. Fetch the posts on the server

Create lib/feedframer.ts. It calls the documented REST endpoint and returns only what the grid needs: top-level posts, with mediaUrl for images and carousels, thumbnailUrl for videos (a video's mediaUrl is usually an MP4) and permalink for the link. Posts without a displayable image are omitted, and any failure returns an empty list rather than breaking the page.

// lib/feedframer.ts
export type Post = {
  id: string;
  mediaType: 'IMAGE' | 'VIDEO' | 'CAROUSEL_ALBUM';
  mediaUrl: string;
  thumbnailUrl: string | null;
  permalink: string;
  altText?: string | null;
};

export type GridPost = { id: string; permalink: string; altText: string; src: string };

export async function getPosts(): Promise<GridPost[]> {
  // Server-only: never prefix this with NEXT_PUBLIC_.
  const apiKey = process.env.FEEDFRAMER_API_KEY;
  if (!apiKey) return [];
  try {
    const params = new URLSearchParams({ api_key: apiKey });
    const res = await fetch(`https://feedframer.com/api/v1/me?${params}`, {
      // Cache for an hour, in line with Feedframer's own edge cache.
      next: { revalidate: 3600 },
    });
    if (!res.ok) {
      console.warn(`Feedframer: request failed with HTTP ${res.status}.`);
      return [];
    }
    const feed = (await res.json()) as { status?: string; posts?: Post[] };
    if (feed.status === 'invalid_token') {
      console.warn('Feedframer: reconnect Instagram in the dashboard. Showing stored posts.');
    }
    const posts = Array.isArray(feed.posts) ? feed.posts : [];
    return posts.flatMap((post) => {
      const src = post.mediaType === 'VIDEO' ? post.thumbnailUrl : post.mediaUrl;
      return src
        ? [{ id: post.id, permalink: post.permalink, altText: post.altText ?? '', src }]
        : [];
    });
  } catch {
    // Do not log request URLs: they contain the account API key.
    console.warn('Feedframer: unable to load Instagram posts.');
    return [];
  }
}

next: { revalidate: 3600 } puts the response in Next.js's data cache for an hour, so visitors are served the cached feed rather than each triggering a request to us.

5. Render the grid

Create components/InstaStrip.tsx. It is an async server component, so the posts are in the HTML on first load and none of this code ships to the browser.

// components/InstaStrip.tsx (a server component: no 'use client')
import Image from 'next/image';
import { getPosts } from '@/lib/feedframer';

export default async function InstaStrip() {
  const posts = await getPosts();

  return (
    <section aria-label="Latest Instagram posts">
      {posts.length > 0 ? (
        <div className="grid grid-cols-3 gap-3 md:grid-cols-6">
          {posts.map((post) => (
            <a key={post.id} href={post.permalink} target="_blank"
               rel="noopener noreferrer" aria-label="View this post on Instagram">
              <Image src={post.src} alt={post.altText} width={400} height={400}
                     sizes="(min-width: 768px) 16vw, 33vw"
                     className="block aspect-square w-full object-cover" />
            </a>
          ))}
        </div>
      ) : (
        <p>Our Instagram posts are temporarily unavailable.</p>
      )}
    </section>
  );
}

Use it from any page or layout:

// app/page.tsx (or any page or layout)
import InstaStrip from '@/components/InstaStrip';

export default function Home() {
  return (
    <main>
      {/* ...the rest of your page */}
      <InstaStrip />
    </main>
  );
}

The classes are Tailwind, which create-next-app sets up by default; if you already have styling, keep your grid and swap just the photo source for post.src. The sample shows a neutral unavailable message after a failed request; in production you may prefer your existing static images as a fallback.

6. Make sure new posts actually reach the page

App Router: the cached response is refreshed at most once an hour. Feedframer imports are daily on Free and hourly on Premium, and the API may be cached for up to an hour, so this is not a real-time Instagram webhook widget.

Pages Router:fetch's next.revalidate option has no effect there. Call the same getPosts() from getStaticProps and let incremental static regeneration refresh the page instead:

// pages/index.tsx
import type { GetStaticProps } from 'next';
import { getPosts, type GridPost } from '@/lib/feedframer';

export const getStaticProps: GetStaticProps<{ posts: GridPost[] }> = async () => ({
  props: { posts: await getPosts() },
  revalidate: 3600, // regenerate the page at most once an hour
});

Static export (output: 'export'): the feed is fetched once at build time. Schedule a rebuild on your host, daily for Free or hourly for Premium if that freshness matters, and add the API key to the build environment. The default next/image optimiser does not run in a static export, so set images.unoptimized: true or use a plain <img>.

Feedframer or Behold for a Next.js Instagram widget?

If you want a live Instagram feed that matches a custom Next.js layout, Feedframer supplies JSON while you control the markup and CSS. We do not meter API calls or website views, we refresh tokens server-side, and you can use REST, GraphQL or RSS. Behold also supplies JSON and has a no-code widget builder, which we do not offer. If you would rather configure a ready-made gallery than maintain a component, Behold can be the better fit. See the current comparison .

Troubleshooting

  • Empty gallery: check FEEDFRAMER_API_KEY is set on the host (then redeploy), the import has finished, and the account has posts.
  • next/image error about an unconfigured hostname: add both hosts to images.remotePatterns and restart the dev server.
  • status: invalid_token: stored posts may still render, but the account owner must reconnect Instagram in the dashboard. Automatic token refresh cannot prevent every password change or revoked permission.
  • Videos missing: the grid needs a thumbnailUrl. It deliberately skips videos without one.
  • Do not use /api/v1/posts or a Bearer header. The endpoint is /api/v1/me?api_key=....

Starters and reference