SvelteKit Infinite Scroll: Instagram API Tutorial

Use Vim Keyboard Shortcuts on your Blog

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).

SvelteKit Infinite Scroll: Screenshot: Image shows a website screenshot with six images from an Instagram feed show in a 3-column grid
SvelteKit Infinite Scroll: Screenshot of feed generated in our app from @askrodney_ Instagram Feed

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.

SvelteKit Infinite Scroll: Screenshot: Instagram A P I key: image is screenshot of an authorisation screen.  User can select level of authorisation and click Allow on Don't Allow
SvelteKit Infinite Scroll: Instagram 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 init [email protected] sveltekit-infinite-scroll && cd $_
pnpm install
pnpm 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:


then include dotenv config in svelte.config.js:

1/** @type {import('@sveltejs/kit').Config} */
2import 'dotenv/config';
3const config = {
4 kit: {
5 // hydrate the <div id="svelte"> element in src/app.html
6 target: '#svelte',
7 },
10export 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:

1export async function get() {
2 try {
3 const url = `,id,media_type,media_url,timestamp&access_token=${process.env['INSTAGRAM_ACCESS_TOKEN']}`;
4 const response = await fetch(url, {
5 method: 'GET',
6 });
8 const data = await response.json();
10 return {
11 body: { },
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 }

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:

2 "data": [
3 {
4 "id": "17924392726111111",
5 "media_type": "IMAGE",
6 "media_url": "",
7 "timestamp": "2021-10-18T11:09:59+0000"
8 },
9 {
10 "id": "17924392726111112",
11 "media_type": "IMAGE",
12 "media_url": "",
13 "timestamp": "2021-10-18T11:09:50+0000"
14 },
15 ],
16 "paging": {
17 "cursors": {
18 "before": "aaa",
19 "after": "bbb"
20 },
21 "next": ""
22 }

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:

1export async function post(request) {
2 try {
3 const { next } = request.body;
4 const response = await fetch(next, {
5 method: 'GET',
6 });
8 const data = await response.json();
10 return {
11 body: { },
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 }

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:

1import { writable } from 'svelte/store';
3const feed = writable([]);
5export { 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 }

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:

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';
24 export let data;
26 const INITIAL_POSTS = 6;
28 const { data: feed, paging } = data;
29 let next = paging?.next ? : null;
30 instagram.set(feed);
32 let limit = INITIAL_POSTS;
34 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 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:

38onMount(() => {
39 if (browser && document.getElementById('footer')) {
40 const handleIntersect = (entries, observer) => {
41 entries.forEach((entry) => {
42 if (!morePostsAvailable()) {
43 observer.unobserve(;
44 }
45 showMorePosts();
46 });
47 };
48 const options = { threshold: 0.25, rootMargin: '-100% 0% 100%' };
49 const observer = new IntersectionObserver(handleIntersect, options);
50 observer.observe(document.getElementById('footer').lastElementChild);
51 }
52 });
54 $: showMorePosts;
55 async function showMorePosts() {
56 try {
57 const newLimit = limit + 6;
58 if (newLimit <= $instagram.length) {
59 // load more images from store
60 limit = newLimit;
61 } else if (next) {
62 // get another page from Instagram if there is another page available
63 const response = await fetch('/api/instagram-feed-more.json', {
64 method: 'POST',
65 credentials: 'same-origin',
66 headers: {
67 'Content-Type': 'application/json',
68 },
69 body: JSON.stringify({ next: next.replace(/%2C/g, ',') }),
70 });
71 const newData = await response.json();
72 const { data: newFeed, next: newNext } = newData;
73 instagram.set([...$instagram, ...newFeed]);
74 next = newNext ?? null;
75 limit = newLimit;
76 }
77 } catch (error) {
78 console.error('Error fetching more posts in index');
79 }
80 }

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.

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:

84 <title>SvelteKit Infinite Feed Scroll</title>
85 <html lang="en-GB" />
87<header>SvelteKit Infinite Scroll</header>
89<main class="container">
90 <h1>Instagram Feed</h1>
91 <section class="feed">
92 {#each $instagram?.slice(0, limit) as { caption, media_url }, index}
93 <article aria-posinset={index + 1} aria-setsize={$instagram.length} class="feed-image">
94 <img
95 class="lazy"
96 alt={caption ? caption : 'Image from instagram feed'}
97 loading="lazy"
98 decoding="async"
99 width="256"
100 height="256"
101 src={media_url}
102 />
103 </article>{:else}
104 No feed images yet!
105 {/each}
106 </section>
108<footer id="footer">
109 <small>Copyright (c) 2021 Rodney Lab. All Rights Reserved.</small>

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 add an id="footer" attribute which is 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.
114 :global(html) {
115 font-family: 'Playfair Display';
116 background: #e1306c;
117 }
118 :global(body) {
119 margin: 0;
120 }
122 header {
123 color: #ffdc80;
124 max-width: 768rem;
125 padding: 1.5rem;
126 font-size: 3.052rem;
127 font-weight: 700;
128 }
129 h1 {
130 color: #ffdc80;
131 font-size: 3.815rem;
132 text-align: center;
133 }
134 .container {
135 min-height: 100vh;
136 }
138 .feed {
139 display: grid;
140 grid-template-columns: 1fr 1fr 1fr;
141 grid-template-rows: auto;
142 row-gap: 0;
143 max-width: 768px;
144 margin: 3rem auto;
145 width: 100%;
146 height: auto;
147 }
149 .feed img {
150 width: 100%;
151 height: 100%;
152 }
153 .feed-image {
154 width: 100%;
155 height: 100%;
156 }
158 footer {
159 background: #833ab4;
160 color: #fff;
161 text-align: center;
162 padding: 1rem;
163 }
165 @media (max-width: 768px) {
166 .feed {
167 padding: 0 1.5rem;
168 width: 100%;
169 }
170 }

πŸ—³οΈ Poll

As a developer which network do you use most?
Voting reveals latest results.

πŸ’― 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: Instagram Test

πŸ™ŒπŸ½ 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.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me…

Rodney from Rodney Lab

Leave a comment …

Your information will be handled in line with our Privacy Policy.