In this tutorial, we're going to guide you on how to restrict your blog readers to only signed in users.

If you need any help following this tutorial, head to our Slack Channel! We're here to help.

Part 1: Cotter Setup

Go to https://dev.cotter.app to create an account. Once you have created an account, make sure to create a new project and grab the API Key ID. We will be using your API Key ID later in part 2.

Part 2: Webflow Setup

For this tutorial, we have created 3 pages: Blog Homepage (/), Sign In Page (/login), and Blog Content Page (/protected). We will be using Webflow CMS to do this. Please refer to this YouTube tutorial to create a simple blog.

Blog Homepage Setup

The Blog Homepage contains a list of your blogs and an overview of each blog. If a reader wants to read the full article, they will be redirected to the Sign In Page where we will show the embedded Cotter login form for your users to type in their email before getting access to the full blog post. If the reader is already signed in, then they will be redirected to the full article page.

Step 1: Add a Sign-in/Sign-out button

Add a button element to redirect users to the Sign In Page. Moreover, we need to set that button ID to "auth-button". This allows the button to be assigned to both "Sign In" and "Sign Out" based on the login status of the user.

Step 2: Add custom code for the Sign-in/Sign-out button logic

After finishing the page setup, we can start with adding custom code to the Blog Homepage. Copy paste the code below to the custom code tab on the Blog Homepage Page settings.

Page Settings
Scroll down to "Custom Code" section

Add the code below to the head of Blog Homepage.

<!--Get Cotter JS SDK-->
<script
    src="https://unpkg.com/[email protected]/dist/cotter.min.js"
    type="text/javascript"
></script>

Add the code below to the body of the Blog Homepage

<script>
  async function checkLoggedIn() {
    // 1. Initialize Cotter
    var cotter = new Cotter("<YOUR_API_KEY_ID>"); // 👈 Specify your API KEY ID
    
    // 2. Check if a user has already logged in
    const accessTokenObject = await cotter.tokenHandler.getAccessToken();
    
    // 3. Change the "Sign In" Button to "Sign Out"
    let authButton = document.getElementById("auth-button");
    if(!accessTokenObject) {
      authButton.innerHTML = "Sign In";
      authButton.addEventListener("click", () => {
        window.localStorage.setItem(
          "redirect_url_after_login", window.location.href
        );
        window.location.href = "/login";
      });
    } else {
      authButton.innerHTML = "Sign Out";
      authButton.addEventListener("click", async () => {
        await cotter.logOut();
        location.reload();
      });
    }
  }
  
  // 4. Call the checkLoggedIn function
  checkLoggedIn();

</script>

Make sure that you have pasted your API Key ID on the code block above. Don't forget to press Save.

Sign In Page Setup (where the sign in form will show up)

Step 1: Add a section to load the Login Form

  • We need to include a section element to load Cotter's login form.
  • Set that section ID to "cotter-form-container".
  • Make the section width and height to 300px for best results.

This enables Cotter's JS SDK to load the login form to the section element that we just added.

Using Cotter's login form, you can combine Sign up and Login into one form since we only require user's email address.

Step 2: Add custom code for the login logic

After finishing the page setup, we can start with adding custom code to the Sign In Page. Copy and paste the code below to the custom code tab on the Sign In Page settings.

  1. Get Cotter JS SDK

Add the code below to the head of Sign In Page.

<!--Get Cotter JS SDK-->
<script
    src="https://unpkg.com/[email protected]/dist/cotter.min.js"
    type="text/javascript"
></script>

2. Initialize Cotter

Add the code below to the body of Sign In Page.

<script>
  // 1. Initialize Cotter
  var cotter = new Cotter("<YOUR_API_KEY_ID>"); // 👈 Specify your API KEY ID
  
  // 2. Get the Redirect URL from Local Storage
  const redirectURL = localStorage.getItem("redirect_url_after_login");
  
  // 3. Display Cotter Login Form
  cotter
    // Choose what method of login do you want
    // Sign In with Magic Link
    .signInWithLink()
    // Send Magic Link via email
    .showEmailForm()
    
    .then(payload => {
      // redirect to previous location (before login page)
      const redirectURL = localStorage.getItem("redirect_url_after_login");
      if(!!redirectURL) window.location.href = redirectURL
      else window.location.href = "/";
    })
    .catch(err => {
      // handle error
    });
</script>

Make sure that you have pasted your API Key ID on the code block above.

You need to Publish your Site to see the login form.

Blog Content Page Setup (full article page)

Now let's move on to the Blog Content page. The Blog Content Page refers to the page that contains your full blog article in which you only want signed in users to access this page.

We'll be adding custom code to the header to:

  1. Check if a user is logged in.
  2. Set the location for redirection after the user is logged in (so that the user will be redirected to the page they were trying to access before being redirected to the Sign In Page).
  3. Fetch the user's OAuth token.

Copy and paste the code below to the custom code tab on the Blog Content Page settings.

Add the code below to the header

<!--Get Cotter JS SDK-->
<script
  src="https://unpkg.com/[email protected]/dist/cotter.min.js"
  type="text/javascript"
></script>

<script>
  async function verifyLogin() {
    // 1. Initialize Cotter
    var cotter = new Cotter("<YOUR_API_KEY_ID>"); // 👈 Specify your API KEY ID
    
    // 2. Check if a user has already logged in
    const accessTokenObject = await cotter.tokenHandler.getAccessToken();
    const accessToken = accessTokenObject ? accessTokenObject.token : null;
    
    // 2a. Set the location for redirection after the user is logged in.
    localStorage.setItem("redirect_url_after_login", window.location.href);

    // 3. If user is not logged in then we redirect to the login page
    if (!accessToken) window.location.href = "/login";

    // 4. Construct the body for access token verification
    let body = {
      oauth_token: {
        access_token: accessToken
      }
    };

    // 5. If user is logged in then we fetch the user data  
    let url = "https://worker.cotter.app/verify";
    fetch(url, {
      method: "POST",
      cache: "no-cache",
      headers: {
        "Content-Type": "application/json",
        API_KEY_ID: "<YOUR_API_KEY_ID>"   // 👈 Specify your API KEY ID here
      },
      mode: "cors",
      body: JSON.stringify(body)
    })
      .then((resp) => resp.json())
      .then((data) => {
        if (!data.success) { window.location.href = "/login" }
      });
  }
  
  // 6. Call the verifyLogin function
  verifyLogin();
  
</script>

Make sure that you have pasted your API Key ID on the code block above.

Part 3: Publish and Test

We've arrived at the last part of this tutorial and all that you need to do is to click publish and test Cotter's magic link authentication for your Webflow blog!


Questions & Feedback

Come and talk to the founders of Cotter and other developers who are using Cotter on Cotter's Slack Channel.

Ready to use Cotter?

If you enjoyed this tutorial and want to integrate Cotter into your website or app, you can create a free account and check out our documentation.

If you need help, ping us on our Slack channel or email us at [email protected]


Build a Simple Blog with #Webflow tutorial by Brian Haferkamp.