Create Ghost Blog Subscription from External Site

Create Ghost Blog Subscription from External Site

·

2 min read

It can be frustrating when you look for information on trying to achieve something and can't find it! I wanted to provide a way to have a subscriber signup for my blog on my personal site which are different online properties. There isn't a lot of information on this but it is definitely hackable and I will briefly show you how.

First, this may not work on a localhost development due to CORS but it does work on a published site at least as of the date of this post.

The Ghost API exposes a "magic" api to achieve this. The URL you need to post data in order to create a subscription is:

https://your-blog-url.com/members/api/send-magic-link/

And what you will want to POST is the following:

{ "email": "me@domain.com", "emailType": "subscribe" }

That's pretty simple right? You can actually proxy this by posting to your server first (ie if you want more control or you encounter CORS errors) or you can post it via fetch (or whatever lib you use). I'll show you both examples here.

Js/Ts example:

// part of a vue component

async subscribe() {
      this.loading = true;
      try {
        const result = await fetch(
          "https://your-blog-url.com/members/api/send-magic-link/",
          {
            method: "POST", // or 'PUT'
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify({ email: this.email, emailType: "subscribe" })
          }
        );

        const r = await result.text();


        if (r != "Created.") alert("bad");
      } catch (e) {
        console.log(e);
      } finally {
        this.loading = false;
      }
    }

That's all you need!

I always like to show how to achieve something in Service Stack on the server side. It is super simple to proxy this request and amounts to only a couple lines of code:

[Route("/subscribe")]
public class BlogSubscribe : IReturn<BlogSubscribeResponse>
{
   public string Email {get;set;}
}


public class BlogSubscribeResponse
{
   public ResponseStatus ResponseStatus {get;set;}
   public bool Success {get;set;}
}

// Inside a service:
 public async Task<BlogSubscribeResponse> Post(BlogSubscribe req)
 {

    var r = await "https://your-blog-url.com/members/api/send-magic-link/".PostJsonToUrlAsync(new { email=req.Email, emailType="subscribe"});

    return new BlogSubscribeResponse () {
        Success = r.Contains("Created")
    }

 }

Boom. Now you can build a form to allow someone to subscribe to your Ghost blog from anywhere in the internet.