Mike Bifulco
BlogWorkAboutNewsletter

Publish your newsletter to your Remix site with the ConvertKit API

Learn how to use the ConvertKit API to publish your newsletter to your Remix site.

I publish a newsletter called Tiny Improvements

My little newsletter is all about making small, incremental improvements to your work and home life. I've been publishing it for over a year now and I've learned a lot about how to make it better.

It's a great way to share less-formal insights with the people who have given me access to their inbox - a privilege which I don't take lightly. It also helps me keep my writing skills sharp, and it's a great way to get direct feedback on my ideas.

Although the audience for my newsletter has been growing, and recently hit some milestones, I realized that I had quite a bit of great writing that went out once, via email, and was never seen again. I wanted to make it easier for people to find and read my past newsletter content without subscribing, as way to show the value it provides. I also wanted to take advantage of the SEO benefits of having past issues of my newsletter content indexed by search engines.

In this post, we'll go over how I use the ConvertKit API to publish a newsletter page for a site built with Remix.

Improve discoverability by publishing past issues

I have a second, important use case for publishing newsletters online. I also maintain my wife's website - primaryfocus.tv - which she uses to promote her business and YouTube channel (go subscribe!).

Primary Focus has a newsletter, and I wanted to make it easy for her to publish her newsletter to her website as well. In fact, I wanted to give her a way to get her newsletter on her website with zero effort - and I was pleased to find that I could do that with the ConvertKit API.

Ideally, the workflow should look like this: newsletters are drafted and published in ConvertKit, and, once sent to her subscribers, automatically published to the website as well. This way, she can focus on writing and sending her newsletter, without adding an additional workflow to update her site.

Her site is built with Remix, so this post will go over the details of implementation for publishing past ConvertKit newsletters to a remix site, using their API.

Using the ConvertKit API to publish newsletters to a Remix site

Setting up an automated newsletter page is fairly simple, at least in theory:

  1. Write newsletters and send them, using ConvertKit's broadcast features (for the sake of this post, we'll use the term "newsletter" and "broadcast" somewhat interchangeably).
  2. Use the ConvertKit API's list-broadcasts endpoint to query for every published broadcast, to populate a newsletter index page
  3. For each published broadcast, use the ConvertKit API to get the details of that broadcast, and then render the content of that broadcast on a page.

To get newsletters from the ConvertKit API, I set up 2 helper functions. First is getNewsletter(), which takes a broadcast ID and returns the details of that broadcast.

export const getNewsletter = async (broadcastId) => {
const res = await fetch(
`https://api.convertkit.com/v3/broadcasts/${broadcastId}?api_secret=${CONVERTKIT_API_SECRET}`
);
// rename "broadcast" to "newsletter" for consistency
const { broadcast: newsletter } = await res.json();
return newsletter;
};

The second is getAllNewsletters(), which returns a list of all published broadcasts. In its simplest form, this function looks like this:

export const getAllNewsletters = async () => {
const response = await fetch(
`https://api.convertkit.com/v3/broadcasts?api_secret=${CONVERTKIT_API_SECRET}`
);
const data = await response.json();
// rename "broadcasts" to "newsletters" for consistency
const { broadcasts: newsletters } = data;
return newsletters;
};

We are using an environment variable to supply the variable CONVERTKIT_API_SECRET - it is super important to keep this value secret, and not share it on the client-side of your app.

Keeping your ConvertKit API Secret key safe on Remix sites

Remix provides a has a handy filename convention to ensure certain code only runs serverside - any file that ends in .server.ts (for TypeScript) and .server.js (for JavaScript) will only be run on the server. This is perfect for keeping our ConvertKit API secret safe. I created a file called /app/lib/util/convertkit.server.js with the two functions above, to make sure to only ever access the secret key in there.

Rendering the newsletter index page

Now that we have a way to get a list of all published newsletters, we can use that to render a page with a preview of each past issue. I created a new file called /app/routes/newsletter/index.jsx to render the newsletter index page.

note: I stripped out the styling/presentation code from this example to keep it focused on data loading logic.

import { useLoaderData } from '@remix-run/react';
import { getAllNewsletters } from '~/lib/util/convertKit.server';
import { NewsletterListItem, NewsletterCTA } from '~/components';
export const loader = async ({ params, request }) => {
return {
newsletters: await getAllNewsletters(),
};
};
const NewsletterListPage = () => {
const { newsletters } = useLoaderData();
return (
<>
<h1>Read past newsletters</h1>
{newsletters.map((newsletter) => (
<NewsletterListItem newsletter={newsletter} key={newsletter.id} />
))}
{/* make sure to add a "hey please subscribe to the newsletter" widget to this page! */}
<NewsletterCTA />
</>
);
};
export default NewsletterListPage;

This is a fairly standard implementation, if you're familiar with Remix. We use the loader pattern to fetch the list of newsletters, and pass them to the render function for the component with the useLoaderData() hook. We then render a list of NewsletterListItem components, which shows a header image and title for each newsletter, along with a link to the page for that specific newsletter.

Rendering a single newsletter page

Now that we have a page listing all published newsletters, we need to create a page template to render a single newsletter. I created a new file called /app/routes/newsletter/$id.jsx to render the newsletter index page (note, once again, that presentation and styling code is removed here for simplicify):

import { useLoaderData } from '@remix-run/react';
import {
broadcastTemplateParse,
newsletterHasValidThumbnail,
} from '~/lib/util/convertKit';
import NewsletterCTA from '~/components';
import config from '~/config';
import { getNewsletter } from '~/lib/util/convertKit.server';
// render meta tags on page for SEO
export const meta = ({ data }) => {
const { newsletter, canonical } = data;
const publishedAt = new Date(newsletter.published_at);
const description = `Primary focus newsletter: ${
newsletter.subject
}, published on ${publishedAt.toLocaleDateString()}`;
return {
description,
title: newsletter.subject
? `${newsletter.subject} - ${config.meta.title}`
: config.meta.title,
'og:image': newsletterHasValidThumbnail(newsletter)
? newsletter.thumbnail_url
: null,
'og:type': 'article',
'og:title': newsletter.subject,
'og:description': description,
'og:url': canonical,
'twitter:card': 'summary_large_image',
};
};
export const loader = async ({ params, request }) => {
const { id } = params;
const newsletter = await getNewsletter(id);
return { newsletter };
};
const NewsletterPage = () => {
const { newsletter } = useLoaderData();
const publishedAt = new Date(newsletter.published_at);
return (
<>
<h1>{newsletter.subject}</h1>
<p className="publish-date">{publishedAt.toLocaleDateString()}</p>
<div
dangerouslySetInnerHTML={{
__html: broadcastTemplateParse({ template: newsletter.content }),
}}
/>
<NewsletterCTA />
</>
);
};
export default NewsletterPage;

Once again, we use the loader pattern to query the ConvertKit API for details about this specific newsletter, and pair that with useLoaderData() to provide that information to the page render function. We also use the meta function pattern to render meta tags for SEO purposes - you can read more about that in the Remix docs.

Render the body using dangersoulySetInnerHTML

To render the contents of the newsletter, we are using a scary-looking React API pattern - dangerouslySetInnerHTML. This is a React API that allows you to render HTML that you have received from an API, and is generally considered a security risk. However, in this case, we are using it to render HTML that we have generated ourselves, and we are at least confident that it is somewhat safe to render. Generally speaking, this is a technique that shouldn't be used unless you are confident that the HTML you are rendering is safe.

Helper functions for displaying ConvertKit newsletter content

We're also using 2 helper functions, which are defined in /app/lib/util/convertKit.js (note that these are not in convertkit.server.js, since we need them on the client side):

import { Liquid } from 'liquidjs';
const engine = new Liquid();
export const broadcastTemplateParse = ({ template, data }) => {
const t = template.replaceAll('&quot;', '"');
const res = engine.parseAndRenderSync(t, data);
return res;
};
export const newsletterHasValidThumbnail = (newsletter) => {
const { thumbnail_url: thumbnailUrl } = newsletter;
if (!thumbnailUrl) return false;
if (thumbnailUrl.startsWith('https://functions-js.convertkit.com/icons'))
return false;
return true;
};

The newsletterHasValidThumbnail function is a helper function that checks if the newsletter has a valid thumbnail image. ConvertKit provides a default thumbnail image for all newsletters, but you can also upload your own, by adding an image to your newsletter's body. This function checks if the thumbnail is the default image, and if so, returns false so we can skip rendering it.

The broadcastTemplateParse function is a helper function that takes a newsletter template and parses it with the Liquid templating language. This is how ConvertKit allows you to customize the HTML of your newsletter, and use dynamic data like the subscriber's name, or the date the newsletter was sent.

An important caveat: There are lots of little cases where this might not work perfectly, due to all of the amazing things you can do with Liquid in ConvertKit. At the moment, my newsletter uses fairly basic liquid customization - this may not do the trick for you if you're using more advanced features. Please test your implementation thoroughly!

Adding more detail to the index page

At the time of writing this post, ConvertKit's v3 API is in "active development" - and as such, it's likely not feature complete. For example, the current API for list-broadcasts provides a minimal amount of data about each broadcast:

curl https://api.convertkit.com/v3/broadcasts?api_secret=<your_secret_api_key>
{
"broadcasts": [
{
"id": 1,
"created_at": "2014-02-13T21:45:16.000Z",
"subject": "Welcome to my Newsletter!"
},
{
"id": 2,
"created_at": "2014-02-20T11:40:11.000Z",
"subject": "Check out my latest blog posts!"
},
{
"id": 3,
"created_at": "2014-02-29T08:21:18.000Z",
"subject": "How to get my free masterclass"
}
]

Since we want to create an index page that shows a thumbnail for each newsletter, we need to query the API for more information about each newsletter. At the moment, the best way to do this is to query the API for each newsletter individually. It's not ideal, since we need to send an API call for each newsletter shown on the index page, but I'm hoping that with a bit of feedback, ConvertKit will add more data to the list-broadcasts API endpoint.

We already have a function to query the API for a single newsletter (remember getNewsletter from earlier?), so we can use that to query the API for each newsletter on the index page.

Filter out un-published newsletters

The list-broadcasts endpoint also doesn't currently return whether or not a given broadcast was published yet - which means that if you draft a future broadcast on your ConvertKit dashboard, it will still be returned by the list API. I don't want to share these yet-to-be-sent newsletters on any of my sites, so we'll add some logic to getAllNewsletters to filter out any newsletters that haven't been published yet.

Don't render newsletters with duplicate subject lines

There are some cases where I send the same newsletter multiple times, with the same subject line, to different audiences - usually because I've forgotten to include some details in the original broadcast. This results in multiple broadcasts with essentially the same content. I don't want to show these on my site, so I added some logic to deduple any newsletters that have the same subject line, displaying only the most recent one (which should be the most correct, in theory).

This is the updated code for getAllNewsletters in convertKit.server.js:

export const getAllNewsletters = async () => {
const response = await fetch(
`https://api.convertkit.com/v3/broadcasts?api_secret=${CONVERTKIT_API_SECRET}`
);
const data = await response.json();
const { broadcasts } = data;
// get details for each individual newsletter
const newsletters = await Promise.all(
broadcasts.map((broadcast) => getNewsletter(broadcast.id))
);
// hackish dedupe here - sometimes we publish a newsletter a _second_ time as a correction, or to a different audience.
// In those cases, they should always have the same subject. We're using subject as a way to deduplicate newsletters in that case
const dedupedBySubject = {};
// return only newsletters that have been published, and sort by most recent to oldest
newsletters
.filter((newsletter) => !!newsletter.published_at)
.sort((a, b) => new Date(b.published_at) - new Date(a.published_at))
.forEach((newsletter) => {
// the first one we encounter in this order will be the newest, so if there's one already we don't make any changes to the object map
if (!dedupedBySubject[newsletter.subject])
dedupedBySubject[newsletter.subject] = newsletter;
});
let nls = [];
// iterate over the map we have of subject->newsletter, and push into a fresh array, which we'll return
for (let subject in dedupedBySubject) {
nls.push(dedupedBySubject[subject]);
}
return nls;
};

And with that, our journey is complete - we've created a /newsletter page that shows a list of all of our newsletters, with a thumbnail image for each one. We've also added a /newsletter/$id page that shows the full content of a given newsletter.

Wrap-up

I hope this post has been helpful to you, and that you've learned something new about how to use ConvertKit's API to create a custom newsletter index page for your Remix site. To see what this looks like in practice, head over to primaryfocus.tv/newsletter.

In my next post, I'll share how I used a similar implementation in Next.js on my site - mikebifulco.com.

If you have any questions, or if you've found a bug in my code, please feel free to reach out to me on Twitter @irreverentmike!

Mike Bifulco headshot

Get content for developers, designers, and entrepreneurs

Subscribe to get my updates delivered to your inbox. Typically 1-2 emails a month, straight from me to you. 😘 Unsubscribe anytime.

***
© 2019-2022 Mike Bifulco
Built with Next. Source code on GitHub.
Disclaimer: 👋🏽 Hi there. I work as a Developer Advocate at Stripe. Content on this site contains my own opinions, and does not necessarily reflect the views of my employer.

More great resources

Articles about React.jsArticles about Remix.runArticles about Next.jsArticles for developersArticles for JavaScript developersArticles about CSSArticles about User Experience (UX)Articles about tools I useArticles about productivityBrowse all topics →