Build your own SvelteKit Boilerplate: Using Mailchimp with Endpoints

Build your own SvelteKit Boilerplate: Using Mailchimp with Endpoints

ยท

5 min read

If you build it, they will come. That's a myth that many developers believe.

A product so good that it sells itself sounds good. But it's also a convenient way to hide from having to do something scary.

Talk to people. Make sales.

We can go halfway there. We will need to get out and sell the product, but not today!

Going halfway there in this case just means making a little form. So let's get started.

I did another stream ๐Ÿ˜€

Again, you can get the code at csellis/svelte-backpack

If you have any questions, you can reach out to me at @elliscs or Chris Ellis.

Integrating Mailchimp using SvelteKit Endpoints

There's a big dilemma in SvelteKit land at the moment. You see, it's built on Vite. Both are really amazing to work with. They are pushing the web forward.

However, it can get pretty damn tricky working with SDKs.

There are a ton of SDKs out there that are built with CommonJS and Vite doesn't currently work well with them.

If you want to go down a rabbit hole, check out https://github.com/vitejs/vite/issues/2579

The net result is that we have to use plain old REST using the Fetch API.

What we'll do

  1. Add an input field to get user emails & hit an endpoint with Fetch
  2. Construct our endpoint
  3. Create an email service that we use for Mailchimp

Adding an Input

// src/routes/index.svelte I should probably break this out, right?

<script>
    import Icon, { Code, Briefcase } from 'svelte-hero-icons';

    let email = '';

    async function handleSubmit() {
        let body = {
            email
        };
        let result = await fetch('/api/registerEmail.json', {
            method: 'post',
            body: JSON.stringify(body)
        });
        const registerEmailResponse = await result.json();
        if (registerEmailResponse.status === 200) {
            email = '';
        }
    }
</script>

We set our email and then we handleSubmit sending email to our yet to be written route, api/registerEmail.json.

<form on:submit|preventDefault={handleSubmit}>
    <input type="text" bind:value={email} />
        <button
            type="submit"
            class="btn bg-secondary-600 hover:bg-secondary-700 text-white text-2xl font-normal px-6 py-4">
               Start Building
        </button>
</form>

We added a form and change the Start Building button from a link to a submit button.

Creating our Endpoint

// src/routes/api/registerEmail.json.js
import mailchimp from '$lib/services/mailchimp';

export async function post({ body }) {
    try {
        let data = await JSON.parse(body);
        let result = await mailchimp.registerEmail(data.email);
        return {
            status: result.status,
            body: result
        };
    } catch (error) {
        console.error(error);
    }
}

That file name looks trippy, amirite?

They explain it more completely here, but basically, we're creating our own HTTP endpoints right in the directories we plan to use them.

We parse the data we send to the route then forward that to our Mailchimp service that we are about to create.

Why not just handle it right here?

Great question, unknown developer!

There's a strong likelihood I will want to extend the Mailchimp integration and it's a nice developer experience having it all available within my own Mailchimp service. This also puts access to my Mailchimp API key another step back from my front end.

In the stream, I asked myself a few times whether I thought the keys would be exposed even here.

To quote a developer from the Svelte Discord channel:

If it is imported to component within route, yes. It will be exposed. If You import it to endpoints or hooks than it will not be exposed

Creating our Mailchimp Service

import dotenv from 'dotenv';
import base64 from 'base-64';
dotenv.config();
let MAILCHIMP_API_KEY = process.env['MAILCHIMP_API_KEY'];

async function registerEmail(email) {
    try {
        // substitute your Mailchimp settings here
        let dc = '';
        let list_id = '';
        let url = `https://${dc}.api.mailchimp.com/3.0/lists/${list_id}/members`;
        let password = MAILCHIMP_API_KEY;

        let data = {
            email_address: email,
            status: 'unsubscribed'
        };

        let headers = new Headers();
        headers.append('Authorization', 'Basic ' + base64.encode('anystring:' + password));

        const response = await fetch(url, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(data)
        });
        const mailchimpResponse = await response.json();
        if (mailchimpResponse) {
            return mailchimpResponse;
        }
    } catch (error) {
        console.error(error);
    }
}

const mailchimp = {
    registerEmail
};

export default mailchimp;

We first need to set and pull in environment variables. I'll leave that up to you to create a .env file with MAILCHIMP_API_KEY as a key.

I can't really show me accessing my key either. I've been burned before streaming a key online. Live and learn.

Then we assemble the code. The URL code that is. With Headers.

We need to encode our password (API key) with Base64. We also have to convert our data to the style object Mailchimp's API creates. Lastly, we curry the response back down to the browser.

We've scaffolded out a way for our boilerplate/starter to collect email addresses. This functionality is vitally important for many websites.

We also have a great model for moving forward. We have an example API call we can use and also an example of using services within a SvelteKit app.

We need to handle the response back down to the browser. There's a huge problem though.

Right now our API is completely open which means a robot could hit it 1k times a second and blow out our free budget of functions and probably lock our Mailchimp. In the next one, I want to explore making this much more difficult.

I would expect your needs might differ from mine. Please let me know what you'd like to see next in this boilerplate at @elliscs or Chris Ellis.

The repo is available at github.com/csellis/svelte-backpack. Feel free to fork, comment, star, etc. Heads up, this is not its final form.

Also, send me a DM if anything was confusing or needs to be reworked.

ย