voorhoede / head-start

Base setup on top of headless services to help you quickly start a new website
ISC License
3 stars 0 forks source link

Social media embeds #107

Closed jbmoelker closed 6 months ago

jbmoelker commented 6 months ago

User story

As a content editor, I want to embed content from social media, so that I can easily enrich a web page with external content.

Possible solution

Use oembed, an open format designed to allow embedding content from a website into another page. OEmbed is supported by many providers (also available as npm package). An OEmbed endpoint returns HTML that can be embedded for a given resource URL (like a URL of a tweet on Twitter).

Example OEmbed usage by astro-embed-twitter:

---
import './Tweet.css';

export interface Props {
    id: string;
}
const { id } = Astro.props;

async function fetchTweet(id: string) {
    try {
        const oembedUrl = new URL('https://publish.twitter.com/oembed');
        oembedUrl.searchParams.set('url', id);
        oembedUrl.searchParams.set('omit_script', 'true');
        oembedUrl.searchParams.set('dnt', 'true');
        return (await fetch(oembedUrl).then((res) => res.json())) as {
            url: string;
            author_name: string;
            author_url: string;
            html: string;
        };
    } catch (e) {
        console.error(
            `[error]  astro-embed
         ${e.status} - ${e.statusText}: Failed to fetch tweet ${id}`
        );
    }
}

const tweet = await fetchTweet(id);
---

{tweet && <astro-embed-tweet set:html={tweet.html} />}

References

Questions?