SvelteKit Infinite Scroll: Instagram API Tutorial # SvelteKit Infinite Scroll: Instagram API Tutorial #
SvelteKit Infinite Scroll: Instagram API Tutorial #
🖱 Infinite Scrolling Feeds in Svelte #
Let's look at SvelteKit infinite scroll. The Instagram app itself is the perfect example of an infinite scrolling feed. There is potentially a large number of posts available and the app does not load them all initially; doing so would slow the page down, impacting user experience. Instead, it loads a few posts and as the user scrolls down, it starts lazy loading more posts. Lazy loading is just a way of saying we load content on demand (or ideally, when we anticipate demand).

We will implement infinite scroll on a SvelteKit app, using images from your Instagram feed. In doing so, we need a trigger for automatically loading more content. For this we can use the Intersection Observer API . When the user scrolls down and the footer becomes visible we will get an observe event and load more content (where there are more posts available). As well as Intersection Observer, from the Svelte toolkit, we will be using a reactive function and stores.
We focus on an Instagram application for infinite scrolling in this article. However, it is not too much effort to apply the techniques here to a blog roll on your site, feeds from other social sites like Twitter or for user interactions on a social app you are building. If that sounds like something you might find useful then why don't we get cracking?
🔑 Instagram Access Token #
We will focus in the SvelteKit side in the post, so that it doesn't get too long. If you want to code along, you will need an Instagram access token. There are currently two Instagram APIs. Here we just want to get images from a particular user's feed and the Instagram Basic Display API matches ours needs. Follow Facebook's Get Started with Instagram Basic Display API to get your access token.

You will see as part of the tutorial, you will set up a test user. Use your own Instagram account (or at least the one you want to extract the feed from). Select the Media (optional) box to be able to pull the feed images in, when asked to authorise your account. Once you have an access token you can move on to the setting up the SvelteKit app.
A temporary access token is fine for a proof of concept, though if you want to pursue the product to production you will eventually need longer living tokens.
⚙️ Svelte Setup #
We'll create a skeleton SvelteKit project and put this thing together from there. To get going, type these commands in the terminal:
pnpm installpnpm install dotenv @fontsource/playfair-display
Select a skeleton project, answer no to Typescript and yes to both Prettier and ESLint. We include
the dotenv
package (as well as a font) in our install so we can read
our Instagram API key from a .env
file. Let's create that file:
1 INSTAGRAM_ACCESS_TOKEN=IGQVJ...
then include dotenv
config in svelte.config.js
:
1 /** @type {import('@sveltejs/kit').Config} */2 import 'dotenv/config';34 const config = {5 kit: { },6 };78 export default config;
Then finally spin up a dev server:
pnpm run dev
🧱 SvelteKit Infinite Scroll: API Routes #
Next we'll build a couple of API routes. We will use these to query the Instagram API from the
client. First create src/routes/api/instargram-feed
(you will need
to create the api
folder). Add the following content:
1 export async function get() {2 try {3 const url = `https://graph.instagram.com/me/media?fields=caption,id,media_type,media_url,timestamp&access_token=${process.env['INSTAGRAM_ACCESS_TOKEN']}`;4 const response = await fetch(url, {5 method: 'GET',6 });78 const data = await response.json();910 return {11 body: { ...data },12 };13 } catch (err) {14 console.log('Error: ', err);15 return {16 status: 500,17 error: 'Error retrieving data in /api.instagram-feed.json',18 };19 }20 }
We will call this code by sending a GET
request to /api-instagram-feed.json
and it will just return the data it receives from Instagram, if all is well! That response will
be JSON and something like this:
1 {2 "data": [3 {4 "id": "17924392726111111",5 "media_type": "IMAGE",6 "media_url": "https://scontent-lhr8-1.cdninstagram.com/v/iamge-url",7 "timestamp": "2021-10-18T11:09:59+0000"8 },9 {10 "id": "17924392726111112",11 "media_type": "IMAGE",12 "media_url": "https://scontent-lhr8-1.cdninstagram.com/v/iamge-url",13 "timestamp": "2021-10-18T11:09:50+0000"14 },15 ],16 "paging": {17 "cursors": {18 "before": "aaa",19 "after": "bbb"20 },21 "next": "https://graph.instagram.com/v12.0/link-for-next-page"22 }23 }
There will be up to 25 posts (I just included two here). Note the paging
object includes a next
link. We will use this when we need to download
more images. Lets code up the endpoint for that next.
Pulling more Images from Instagram API #
To get more images, we just need the next
link included in the previous
call. Create an endpoint for pulling more images at src/routes/api/instagram-feed-more.json.js
and add this content:
1 export async function post(request) {2 try {3 const { next } = request.body;4 const response = await fetch(next, {5 method: 'GET',6 });78 const data = await response.json();910 return {11 body: { ...data },12 };13 } catch (err) {14 console.log('Error: ', err);15 return {16 status: 500,17 error: 'Error retrieving data in /api.instagram-feed-more.json',18 };19 }20 }
We will access this endpoint using the POST
method and include the
next
link in the API call body.
With our API routes now all set up, let's add one more piece of plumbing before we code up the client page.
🛍 Svelte Store #
Initially, we will show six images, though we would have pulled up to 25 in the first API call.
The store helps us out here. We put all the images we pulled from Instagram into the store and
then (initially) show the first six. As the user scrolls down, we will load more images from the
store. Eventually, it's possible the user will want more images than there are available in the
store. At that point we make a more
Instagram call, returning up to
25 more images. We append those new images onto the end of what's in the store already and we're away!
That probably sounded more complicated than Svelte actually makes it, but I wanted to run through
the logic before we implement it. As it happens, we only need three lines of JavaScript to set
this store up in SvelteKit! Create a file at src/lib/shared/store/instagram.js
(you will need to create some folders). Add these lines to the file:
1 import { writable } from 'svelte/store';23 const feed = writable([]);45 export { feed as default };
In line 3
, we are initialising the store to an empty array. Let's
add something now from the client.
🧑🏽 Client Side #
We'll start with the load function. In SvelteKit, load functions run before the initial render.
Here it makes sense to make the first Instagram call in the load function. Replace the existing
code in src/routes/index.svelte
:
1 <script context="module">2 export async function load({ fetch }) {3 try {4 const response = await fetch('/api/instagram-feed.json', {5 method: 'GET',6 credentials: 'same-origin',7 });8 return {9 props: { data: { ...(await response.json()) } },10 };11 } catch (error) {12 console.error(error);13 }14 }15 </script>
You see we call the first API route we created, sending a GET
request.
Stocking up the Store #
You might have noticed, we returned props from the load function in line 9
. This makes the Instagram data available to our client side JavaScript, which we add next:
17 <script>18 import instagram from '$lib/shared/stores/instagram';19 import { onMount } from 'svelte';20 import { browser } from '$app/env';21 import '@fontsource/playfair-display/400.css';22 import '@fontsource/playfair-display/700.css';2324 export let data;2526 const INITIAL_POSTS = 6;2728 const { data: feed, paging } = data;29 let next = paging?.next ? paging.next : null;30 instagram.set(feed);3132 let limit = INITIAL_POSTS;3334 function morePostsAvailable() {35 return limit < $instagram.length || next;36 }
We have the feed posts available in the data prop, which we import (Svelte syntax is to use the export-astro
keyword here) in line 24. We destructure the feed and then adding the data to the store is simply
done in line 30
with instagram.set(feed)
. Could there be less boiler plate? 😅
I should mention, we imported the store in line 18
. In line 35
you see an example of how we can access the store. We just write $instagram
and that gives us the array which we set the store to be. In this line, we check how many elements
are currently in the store array.
Intersection Observer #
Okay, next we want to be able to show more posts (if we have them) whenever the footer comes into
view. The Intersection Observer API is our friend here. If this is your first time using it in
Svelte, check out the post on tracking page views, where we look at Intersection Observer
in more detail. Add this code to the bottom of src/routes/index.svelte
:
38 let footer;3940 onMount(() => {41 if (browser) {42 const handleIntersect = (entries, observer) => {43 entries.forEach((entry) => {44 if (!morePostsAvailable()) {45 observer.unobserve(entry.target);46 }47 showMorePosts();48 });49 };50 const options = { threshold: 0.5, rootMargin: '-100% 0% 100%' };51 const observer = new IntersectionObserver(handleIntersect, options);52 observer.observe(footer);53 }54 });5556 $: showMorePosts;57 async function showMorePosts() {58 try {59 const newLimit = limit + 6;60 if (newLimit <= $instagram.length) {61 // load more images from store62 limit = newLimit;63 } else if (next) {64 // get another page from IG if there is another page available65 const response = await fetch('/api/instagram-feed-more.json', {66 method: 'POST',67 credentials: 'same-origin',68 headers: {69 'Content-Type': 'application/json',70 },71 body: JSON.stringify({ next: next.replace(/%2C/g, ',') }),72 });73 const newData = await response.json();74 const { data: newFeed, next: newNext } = newData;75 instagram.set([...$instagram, ...newFeed]);76 next = newNext ?? null;77 limit = newLimit;78 }79 } catch (error) {80 console.error('Error fetching more posts in index');81 }82 }83 </script>
We will set the minimum page height so that the footer is initially out of view (in styles which
we add in a moment). Our Intersection Observer parameters will observe an intersection event when
the user scrolls down and the footer becomes visible. This will call the showMorePosts
function. To help here we will bind the footer
variable (in line 38
) to the actual rendered footer element.
showMorePosts
is declared as a reactive function (in line 54
). This is a hint to the Svelte compiler that the function changes some elements in the DOM and
a refresh might be needed when it is finished.
In line 69
, we just make sure we replace URL encoded commas in the next
string with actual commas. Let me know if anything here needs more explanation and I can update
the post. Let's actually render the content next.
Client Rendered Markup #
Paste this code at the bottom of src/routes/index.svelte
:
83 <svelte:head>84 <title>SvelteKit Infinite Feed Scroll</title>85 <html lang="en-GB" />86 </svelte:head>8788 <header>SvelteKit Infinite Scroll</header>8990 <main class="container">91 <h1>Instagram Feed</h1>92 <section class="feed">93 {#each $instagram?.slice(0, limit) as { caption, media_url }, index}94 <article aria-posinset={index + 1} aria-setsize={$instagram.length} class="feed-image">95 <img96 class="lazy"97 alt={caption ? caption : 'Image from instagram feed'}98 loading="lazy"99 decoding="async"100 width="256"101 height="256"102 src={media_url}103 />104 </article>{:else}105 No feed images yet!106 {/each}107 </section>108 </main>109 <footer bind:this={footer}>110 <small>Copyright (c) 2021 Rodney Lab. All Rights Reserved.</small>111 </footer>
There's a few things worth mentioning here:
-
in line
93
we just take the number of posts we want from the store, rather that the whole thing, -
we use
bind:this
to attach the footer element to the variable we mentioned before, used above by the Intersection Observer code, - I've just included the footer content in the example for the sake of the Intersection Observer code.
SvelteKit Infinite Scroll: Styling #
Here's some (mostly) optional styling, just paste it at the bottom of our file. Be sure at least
to set the min-height
as in line 135
:
src/routes/index.svelte
— click to expand code.
113 <style>114 :global(html) {115 font-family: 'Playfair Display';116 background: #e1306c;117 }118 :global(body) {119 margin: 0;120 }121 :global(:root) {122 --font-weight-bold: 700;123 }124125 header {126 color: #ffdc80;127 max-width: 768rem;128 padding: 1.5rem;129 font-size: 3.052rem;130 font-weight: var(--font-weight-bold);131 }132 h1 {133 color: #ffdc80;134 font-size: 3.815rem;135 text-align: center;136 }137 .container {138 min-height: 100vh;139 }140141 .feed {142 display: grid;143 grid-template-columns: 1fr 1fr 1fr;144 grid-template-rows: auto;145 row-gap: 0;146 max-width: 768px;147 margin: 3rem auto;148 width: 100%;149 height: auto;150 }151152 .feed img {153 width: 100%;154 height: 100%;155 }156 .feed-image {157 width: 100%;158 height: 100%;159 }160161 footer {162 background: #833ab4;163 color: #fff;164 text-align: center;165 padding: 1rem;166 }167168 @media (max-width: 768px) {169 .feed {170 padding: 0 1.5rem;171 width: 100%;172 }173 }174 </style>
🗳 Poll #
💯 SvelteKit Infinite Scroll: Testing #
That's it. Give your browser a refresh and get scrolling! If your internet connection is fast you might not notice more images loading. Keen an eye on the vertical scroll bar though and you will see it jumps as more content (off screen) loads.
🙌🏽 SvelteKit Infinite Scroll: What we Learned #
In this post we learned:
- using the Instagram API to fetch a user's posts,
- how you can use store in Svelte to buffer content received from an external feed,
- combining the Intersection Observer API with Svelte stores for a seamless user experience.
I do hope there is at least one thing in this article which you can use in your work or a side project. For extensions, you could add a Twitter or try adapting the code to take Instagram Video posts as well as images. Alternatively simply use the code to create an infinite feed of your blog posts. The sky is the limit, you can really go to town on this!
As always get in touch with feedback if I have missed a trick somewhere! You can see the full code for this SvelteKit Instagram Infinite Scroll tutorial on the Rodney Lab Git Hub repo .
🙏🏽 SvelteKit Infinite Scroll: Feedback #
Have you found the post useful? Do you have your own methods for solving this problem? Let me know your solution. Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee .
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab . I post regularly on SvelteKit as well as other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.
