DEV Community

Cover image for Showing Live Credly Badges on My SvelteKit Portfolio (No API Key, No CORS Headaches)
jbcanillo
jbcanillo

Posted on

Showing Live Credly Badges on My SvelteKit Portfolio (No API Key, No CORS Headaches)

My portfolio had an "Affiliations" section with four static logos that I hadn't touched in ages. Meanwhile, my actual proof of learning, a stack of IBM and Coursera badges on Credly, sat on a different website that nobody visiting my portfolio would ever click through to.

So I replaced that section with a Certifications & badges carousel that reads straight from my Credly profile. When I earn a new badge, it shows up on jbcanillo.netlify.app by itself. I don't edit a file or redeploy.

Here's how it works, and the three small problems I had to solve along the way.

The stack

  • SvelteKit (Svelte 4), prerendered to static HTML
  • Skeleton UI + Tailwind CSS
  • Netlify via @sveltejs/adapter-netlify

The whole site is static. That matters later.

// src/routes/+layout.ts
// The whole site is static content, so render every page to HTML at build time.
export const prerender = true;
Enter fullscreen mode Exit fullscreen mode

Problem 1: Credly has no "embed my badges" API key flow

Credly's official API is aimed at issuers (organizations that award badges), not earners. But every public Credly profile exposes its badges as JSON:

https://www.credly.com/users/<your-username>/badges.json
Enter fullscreen mode Exit fullscreen mode

No API key, no OAuth. Open yours in a browser and you'll see a data array with every badge: template name, issuer, issue date, image URL and state.

Problem 2: The browser can't read it (CORS)

My first thought was to just fetch() it from the profile page. That fails. Credly sends no CORS headers on that endpoint, so the browser blocks the response.

The fix is to fetch it server-side and expose it from my own origin. In SvelteKit that's a +server.ts route. Because the site defaults to prerender = true, I opt this one route out so it runs at request time. On Netlify, adapter-netlify turns it into a Netlify Function automatically.

// src/routes/api/badges/+server.ts
import { json } from '@sveltejs/kit';
import { credlyUser, type Badge } from '$lib/data/profile';
import type { RequestHandler } from './$types';

// Runs on the server (a Netlify function) at request time, unlike the rest of the site.
export const prerender = false;

/** Credly serves resized copies of badge images; the originals are over 500 KB each. */
function thumbnail(url: string) {
    return url.replace(
        'https://images.credly.com/images/',
        'https://images.credly.com/size/220x220/images/'
    );
}

export const GET: RequestHandler = async ({ fetch, setHeaders }) => {
    const response = await fetch(
        `https://www.credly.com/users/${credlyUser}/badges.json?page=1&page_size=48`,
        { headers: { accept: 'application/json' } }
    );
    if (!response.ok) {
        return json({ error: `Credly responded with ${response.status}` }, { status: 502 });
    }

    const body = await response.json();
    const badges: Badge[] = (body.data ?? [])
        .filter((item: any) => item.public !== false && item.state === 'accepted')
        .map((item: any) => ({
            name: item.badge_template?.name ?? '',
            issuer: (item.issuer?.entities ?? []).map((e: any) => e.entity?.name).join(' / '),
            issued: item.issued_at_date ?? '',
            url: `https://www.credly.com/badges/${item.id}/public_url`,
            src: thumbnail(item.image_url ?? item.badge_template?.image_url ?? '')
        }))
        .filter((badge: Badge) => badge.name && badge.src);

    setHeaders({ 'cache-control': 'public, max-age=300, s-maxage=21600' });
    return json({ badges });
};
Enter fullscreen mode Exit fullscreen mode

A few details worth pointing out:

  • Filtering. I only keep badges that are public and accepted, so pending or hidden badges never leak onto the site.
  • Issuer names. A badge can have more than one issuing entity (mine are "Coursera / IBM"), so I join them.
  • Image size. The original badge PNGs are over 500 KB each. Credly also serves resized copies under /size/220x220/, so a one-line replace cuts the payload massively. The carousel renders them at 110px, so 220px covers 2x screens.
  • Verification link. Each card links to the badge's public_url, so anyone can confirm it's real.

Problem 3: Don't hammer Credly, and don't break when it's down

That cache-control header does most of the work:

public, max-age=300, s-maxage=21600
Enter fullscreen mode Exit fullscreen mode
  • s-maxage=21600 tells Netlify's CDN to cache the response for six hours. The function, and therefore Credly, gets hit at most a few times a day, not once per visitor.
  • max-age=300 lets browsers reuse it for five minutes.

New badges show up within six hours, which is plenty for a portfolio.

For resilience, I also keep a bundled snapshot of my badges in the repo, with images saved locally as .webp:

// src/lib/data/profile.ts
export interface Badge {
    name: string;
    issuer: string;
    /** ISO date, e.g. 2024-11-03 */
    issued: string;
    url: string;
    src: string;
}

export const credlyUser = 'julius-brian-canillo';
export const credlyProfile = `https://www.credly.com/users/${credlyUser}`;

/**
 * Snapshot of the public Credly profile, newest first. The profile page shows this
 * immediately and then replaces it with the live list from /api/badges, so new badges
 * appear without editing this file. The snapshot is what visitors see if Credly is down.
 */
export const badges: Badge[] = [
    {
        name: 'Back-end Application Development Capstone Project',
        issuer: 'Coursera / IBM',
        issued: '2024-11-03',
        url: 'https://www.credly.com/badges/4d3c2dce-19e2-43a7-9d48-fb80e7d409a1/public_url',
        src: '/images/badges/back-end-application-development-capstone-project.webp'
    }
    // ...13 more
];
Enter fullscreen mode Exit fullscreen mode

Wiring it into the page

The profile page is prerendered with the snapshot already in the HTML, so badges are visible on first paint and search engines see them. After the page mounts, it quietly swaps in the live list:

<script lang="ts">
    import { onMount } from 'svelte';
    import BadgeCarousel from '$lib/components/BadgeCarousel.svelte';
    import { badges as badgeSnapshot, credlyProfile, type Badge } from '$lib/data/profile';

    // Start from the bundled snapshot, then swap in the live list from Credly
    // (through this site's /api/badges endpoint) so newly earned badges show up by themselves.
    let badges: Badge[] = badgeSnapshot;
    onMount(async () => {
        try {
            const response = await fetch('/api/badges');
            if (!response.ok) return;
            const live = (await response.json()).badges;
            if (Array.isArray(live) && live.length) badges = live;
        } catch {
            // Keep the snapshot
        }
    });
</script>

<section class="card variant-ghost flex min-w-0 flex-col p-5 shadow-md">
    <div class="mb-4 flex flex-wrap items-baseline justify-between gap-2">
        <h2 class="h3 font-bold">Certifications &amp; badges</h2>
        <a class="text-sm underline" href={credlyProfile} target="_blank" rel="noreferrer">
            Verified on Credly
        </a>
    </div>
    <BadgeCarousel {badges} />
    <p class="mt-3 text-center text-sm opacity-70">{badges.length} badges</p>
</section>
Enter fullscreen mode Exit fullscreen mode

If the endpoint errors, returns an empty list or the network fails, nothing visible happens. The snapshot just stays.

The carousel

I didn't want another carousel library, so BadgeCarousel.svelte is a native horizontal scroll container with CSS scroll snapping. That means swiping on phones and keyboard scrolling work for free. On top of that it adds:

  • previous/next arrow buttons that wrap around at either end
  • autoplay every 3 seconds, paused on hover or keyboard focus
  • no autoplay at all for visitors with prefers-reduced-motion: reduce
<script lang="ts">
    import { onMount } from 'svelte';
    import type { Badge } from '$lib/data/profile';

    export let badges: Badge[] = [];
    export let interval = 3000;

    let track: HTMLUListElement;
    let paused = false;

    function step(direction: 1 | -1) {
        if (!track) return;
        const item = track.querySelector('li');
        const size = item ? item.getBoundingClientRect().width + 12 : 172;
        const end = track.scrollWidth - track.clientWidth;
        if (direction === 1 && track.scrollLeft >= end - 4) {
            track.scrollTo({ left: 0, behavior: 'smooth' });
        } else if (direction === -1 && track.scrollLeft <= 4) {
            track.scrollTo({ left: end, behavior: 'smooth' });
        } else {
            track.scrollBy({ left: direction * size, behavior: 'smooth' });
        }
    }

    onMount(() => {
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
        const timer = setInterval(() => {
            if (!paused) step(1);
        }, interval);
        return () => clearInterval(timer);
    });
</script>

<div
    class="flex items-center gap-2"
    on:mouseenter={() => (paused = true)}
    on:mouseleave={() => (paused = false)}
    on:focusin={() => (paused = true)}
    on:focusout={() => (paused = false)}
>
    <button type="button" class="btn-icon btn-icon-sm variant-soft" aria-label="Previous badges" on:click={() => step(-1)}>
        <i class="fa fa-chevron-left" aria-hidden="true"></i>
    </button>

    <ul bind:this={track} class="track flex min-w-0 flex-1 gap-3 overflow-x-auto py-1">
        {#each badges as badge (badge.url)}
            <li class="w-40 shrink-0">
                <a href={badge.url} target="_blank" rel="noreferrer"
                    class="card card-hover variant-soft flex h-full flex-col items-center gap-2 p-3 text-center">
                    <img src={badge.src} alt="" width="110" height="110" loading="lazy"
                        class="h-[110px] w-[110px] rounded-full object-contain" />
                    <span class="text-xs font-bold leading-snug">{badge.name}</span>
                    <span class="mt-auto text-xs opacity-70">
                        {badge.issuer} · {badge.issued.slice(0, 4)}
                    </span>
                </a>
            </li>
        {/each}
    </ul>

    <button type="button" class="btn-icon btn-icon-sm variant-soft" aria-label="Next badges" on:click={() => step(1)}>
        <i class="fa fa-chevron-right" aria-hidden="true"></i>
    </button>
</div>

<style>
    .track {
        scroll-snap-type: x mandatory;
        scrollbar-width: none;
    }
    .track::-webkit-scrollbar {
        display: none;
    }
    .track > :global(li) {
        scroll-snap-align: start;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

The image alt is empty on purpose. The badge name is right below it as text, so a screen reader would otherwise read it twice.

Recap

Concern Solution
No earner API key Public /users/<user>/badges.json
CORS blocks the browser SvelteKit +server.ts route (prerender = false), deployed as a Netlify Function
500 KB+ images Rewrite to Credly's /size/220x220/ URLs
Rate limits / load s-maxage=21600, a six-hour CDN cache
Credly downtime, SEO, first paint Bundled snapshot rendered at build time, replaced after mount
Accessibility Native scroll + snap, pause on focus, respects reduced motion

A word of caution: badges.json is a public but undocumented endpoint, so Credly could change its shape at any time. That's exactly why the snapshot exists. If the live call ever breaks, the site keeps showing the last known badges instead of an empty box.

If you have a Credly profile and a static site, this pattern takes about 50 lines of code. The source is on GitHub at jbcanillo/portfolio-site, and you can see the result on my profile page.

Thanks for reading! If you've integrated Credly (or Accredible, or Badgr) another way, I'd love to hear how in the comments.

Top comments (0)