Build your own SvelteKit Boilerplate: Using Mailchimp with Endpoints

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 😀

Stream no longer available

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?

<span>&lt;<span>script</span>&gt;</span><span>
    <span>import</span> Icon, { Code, Briefcase } <span>from</span> <span>'svelte-hero-icons'</span>;

    <span>let</span> email = <span>''</span>;

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

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

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

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

Creating our Endpoint