Building a Dynamic Instagram Social Media Slider with SitecoreAI and Next.js
Friday, Nov 6, 2026
Summary
Integrating Instagram content into a website is a great way to keep content fresh, improve user engagement, and showcase a brand's social presence.
In this article, we will explore how to build a reusable Social Media Slider component using SitecoreAI, Next.js, and the Sitecore Content SDK. The implementation retrieves Instagram posts dynamically through a backend API and displays them using a reusable React component.
Overview
The implementation is organized into separate files to keep Sitecore integration, data models, API communication, and UI rendering independent.
SocialMediaSliderTypes.ts
Defines TypeScript interfaces for the Sitecore GraphQL datasource, Instagram account information, and Social Media Slider component properties.
SocialMediaSlider-Sitecore.tsx
Handles Sitecore datasource retrieval, extracts Instagram account credentials, calls the Next.js API endpoint, maps the Instagram response, and passes the data to the slider component.
SocialMediaSlider.tsx
Contains the reusable React presentation component responsible for displaying Instagram posts in a slider, including title, account name, and animation configuration.
1. Define the Sitecore Data Structure
The first step is to define the data structure required by the Social Media Slider component. The SocialMediaSliderTypes.ts file contains the TypeScript interfaces representing the Sitecore datasource and component properties.
import type { Field } from "@sitecore-content-sdk/nextjs";
import type { ComponentProps } from "@/lib/component-props";
export interface SocialMediaSliderGqlData {
title: { jsonValue: Field<string> } | null;
accountName: {
jsonValue: InstaAccountItem;
} | null;
}
export interface InstaAccountItem {
id: string;
url: string;
name: string;
fields: {
"Access Token": { value: string };
"Expires On": { value: string };
"Account Id": { value: string };
};
}
export type SocialMediaSliderScProps = ComponentProps & {
fields: {
data: {
socialMediaSliderData:
SocialMediaSliderGqlData | null;
};
};
};
The Instagram account datasource contains the account ID, access token, and token expiration information. This allows content authors to manage Instagram account configuration through Sitecore rather than hardcoding account details in the application.

2. Retrieve Instagram Account Details from Sitecore
The SocialMediaSlider-Sitecore.tsx Before processing the Instagram account information, the implementation checks whether the datasource exists. component acts as the integration layer between Sitecore and the reusable Social Media Slider component.
First, retrieve the datasource information. Before processing the Instagram account information, the implementation checks whether the datasource exists.
const data =
props.fields?.data?.socialMediaSliderData;
if (!data) {
return (
<div className="component ig-slider">
Social Media Slider content not available.
</div>
);
}
Next, retrieve the Instagram account ID and access token from the referenced account datasource.
const accountId =
data.accountName?.jsonValue?.fields?.["Account Id"]?.value;
const token =
data.accountName?.jsonValue?.fields?.["Access Token"]?.value;
These values are required to authenticate requests to the Instagram integration API.
3. Fetch Instagram Posts Through a Next.js API
Once the account details are available, prepare the API request using URLSearchParams.
const params = new URLSearchParams();
params.set("accountId", accountId);
params.set("token", token);
const response = await fetch(
\`\${process.env.NEXT_PUBLIC_SITECORE_WEBSITE_URL}/api/social-media/instagram/get-posts/?\${params.toString()}\`,
{
method: "GET",
cache: "no-store",
headers: {
"x-internal-key": process.env.INTERNAL_API_KEY!,
},
},
);
if (!response.ok) {
throw new Error("Failed to load Instagram posts!");
}
const igPosts = await response.json();
const posts = igPosts?.data ?? [];
The backend API handles communication with Instagram and returns the available posts. The internal API key is passed through a server-side request header and should never be exposed through a NEXT_PUBLIC_ environment variable.
and here is the .../api/social-media/instagram/get-posts API
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) {
const internalKey = req.headers.get("x-internal-key");
if (internalKey !== process.env.INTERNAL_API_KEY) {
return new Response("Unauthorized", { status: 401 });
}
const instaUrl = process.env.INSTAGRAM_API_Url!;
const { searchParams } = req.nextUrl;
const accountId = searchParams.get("accountId") ?? "";
const token = searchParams.get("token") ?? "";
const url = instaUrl.replace("{0}", accountId).replace("{1}", token);
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
return NextResponse.json(data);
}
Learn more about Instagram API here...
4. Map Instagram API Data to the Component Model
The Instagram API response may have a different structure from the model expected by the Social Media Slider. To keep the presentation component independent of the external API response, use a mapping function.
function mapItem(item: any): InstagramPost {
return {
id: item.id,
permalink: item.permalink,
caption: item.caption,
media_url: item.media_url,
media_type: item.media_type,
thumbnail_url: item.thumbnail_url,
username: item.username,
postDuration: item.timestamp,
};
}
This function transforms the Instagram response into the application's InstagramPost model. Using a separate mapping function makes it easier to maintain the integration if the external API response or component model changes.
5. Render the Reusable Social Media Slider
This step focuses on building a reusable React component SocialMediaSlider.tsx that displays Instagram posts in a responsive carousel. The component uses Swiper for carousel functionality, Next.js Image for optimized images, and Next.js Link to navigate to Instagram posts and profiles.
Rather than including the entire component implementation, the following are the essential sections:
Define the post and component properties
export interface InstagramPost {
id: string;
permalink: string;
caption: string;
media_url: string;
thumbnail_url?: string;
media_type: string;
username: string;
postDuration?: string;
}
export interface SocialMediaSliderProps {
title?: string | React.JSX.Element;
accountName?: string;
accountUsername?: string;
headerLogo?: React.JSX.Element;
enableAnimation?: boolean;
posts?: InstagramPost[];
}
These interfaces define the data received from the Sitecore integration. They include Instagram post details, account information, optional branding, and the animation setting.
Configure the carousel behavior
const swiperRef = useRef<SwiperType | null>(null);
const [activeIndex, setActiveIndex] = useState(0);
const [isPlaying, setIsPlaying] = useState(enableAnimation);
const loopEnabled = posts.length > 1;
const desktopSlidesPerView = Math.min(3, posts.length);
The component uses React state to track the active slide and autoplay status. It enables infinite looping when there is more than one post and displays up to three posts on desktop screens.
Render the Instagram posts using Swiper
{posts.length > 0 && (
<Swiper
slidesPerView={1}
spaceBetween={14}
breakpoints={{
960: {
slidesPerView: desktopSlidesPerView,
spaceBetween: 14,
},
}}
loop={loopEnabled}
modules={enableAnimation ? [Autoplay] : []}
autoplay={
enableAnimation
? { delay: 4000, disableOnInteraction: true }
: false
}
onSwiper={(swiper) => {
swiperRef.current = swiper;
syncSwiperSlideInert(swiper);
}}
onSlideChange={(swiper) => setActiveIndex(swiper.realIndex)}
>
{posts.map((post) => {
const isVideo = post.media_type.toLowerCase() === "video";
const thumbnailSrc = post.thumbnail_url ?? post.media_url;
return (
<SwiperSlide key={post.id}>
<Link
href={post.permalink}
target="_blank"
rel="noopener noreferrer"
>
<Image
src={thumbnailSrc}
alt=""
width={400}
height={400}
/>
{isVideo && <PlayIconSvg />}
<div className="branding">
<span>{accountName ?? post.username}</span>
{post.postDuration && (
<span>{getDuration(post.postDuration)}</span>
)}
</div>
</Link>
</SwiperSlide>
);
})}
</Swiper>
)}
This is the core rendering logic. It loops through the Instagram posts and creates a slide for each one. The component uses the thumbnail URL when available, otherwise it falls back to the media URL. Video posts display a play icon, and each slide links to its original Instagram post. The carousel shows one slide on smaller screens and up to three on desktop, with optional autoplay every four seconds.
Add navigation and accessibility controls
The component also includes previous and next buttons, an autoplay toggle, and a live region that announces slide changes to screen readers. These controls reuse the existing utilities from the LogoSlider component, including PrevArrowSvg, NextArrowSvg, CarouselLiveRegion, AutoplayToggle, and syncSwiperSlideInert.
Display account information and post dates
The header displays the account title, optional logo, and a Follow Us link. The getPostDuration() and getDuration() helper functions calculate and format the time since each post was published, displaying labels such as Posted Today, Posted Yesterday, or Posted X days ago.
Finally, the component imports social-media-slider.scss for styling and can be reused wherever the Sitecore Social Media Slider rendering is required.

6. Production Considerations and Best Practices
Before using this implementation in production, consider the following improvements:
Secure credentials: Avoid passing access tokens through query parameters. Prefer protected server-to-server requests and secure server-side credential storage.
Handle API failures: Provide fallback rendering for expired tokens, API failures, and unavailable Instagram content.
Optimize performance: Consider caching Instagram responses instead of fetching fresh data on every page request.
Handle empty responses: Add appropriate handling when no Instagram posts are returned, especially because the title and account name currently depend on posts[0]?.username.
Review image configuration: Ensure the Instagram image hostnames are configured correctly for the Next.js Image component.
Maintain accessibility: Preserve keyboard navigation, screen-reader announcements, and inactive-slide accessibility behavior when modifying the carousel.
These improvements help make the integration more secure, reliable, and efficient.
7. Instagram Access Token Management
Instagram access tokens have a maximum validity period of 60 days and must be refreshed proactively to prevent expiration and avoid interruptions in retrieving Instagram posts.
To automate this process, A scheduled CRON job should be configured to run weekly at a predefined time and automatically refresh any access tokens that are approaching expiration.
This proactive token management approach helps maintain uninterrupted access to Instagram data while reducing the need for manual token renewal.
Conclusion
Building a dynamic Instagram Social Media Slider with SitecoreAI and Next.js provides a flexible way to display social media content directly on a website.
By separating Sitecore datasource retrieval, backend API integration, data mapping, and UI rendering, we can create a reusable and maintainable solution.
The seven steps outlined in this article provide a foundation for integrating external social media content into a SitecoreAI application while keeping the implementation clean and extensible.