Stop spending days to code your login page! Add Cotter's magic link to your Gatsby app under 5 minutes
Tags: guides, tutorials
Published: 2020-07-07 18:01:50

---
title: Stop spending days to code your login page! Add Cotter's magic link to your Gatsby app under 5 minutes
published: true
date: 2020-07-02 01:27:27 UTC
tags: Guides,Tutorials
canonical_url: https://blog.cotter.app/stop-spending-days-to-code-your-login-page-add-cotters-magic-link-to-your-gatsby-app-under-5-minutes/
---
*Supercharge your Gatsby app's authentication system with Cotter's magic link. Like how Slack does it, but simpler.*

 ![Stop spending days to code your login page! Add Cotter's magic link to your Gatsby app under 5 minutes](https://blog.cotter.app/content/images/2020/06/Cover-1.png)

In this guide, we'll show you how to integrate Cotter's magic link authentication to Gatsby.

## Let's get started

**a. Install Gatsby**

```
# If you don't have Gatsby installed, run
npm install -g gatsby-cli
# Check if Gatsby exist
gatsby -v
```
<figcaption>Our current version: Gatsby CLI version: 2.12.15</figcaption>

**b. Create New Gatsby Project**

Let's start with an empty Gatsby project and name it `gatsby-cotter`.

```
gatsby new gatsby-cotter
cd gatsby-cotter && gatsby develop
```
<figcaption>This will create a new gatsby project with the name gatsby-cotter</figcaption>

Head to `src/pages/index.js` and modify the default Gatsby homepage HTML template by copy pasting the code below:

```react
import React, { useState, useEffect } from "react"; // 👈 Add useEffect here!
// 2️⃣ TODO: Import Cotter

import "./styles.css";

const IndexPage = () => {
  const [responsePayload, setResponsePayload] = useState(null);
  const [loggedIn, setLoggedIn] = useState(false);

  // 3️⃣ TODO: Initialize Cotter and show the form

  return (
    <div className="container">
      <h1 className="title">Passwordless App.</h1>

      {/* 1️⃣ TODO: Setup a div to contain the form */}

      <div id="user-info">
        { loggedIn ? `Welcome, ${responsePayload.email}` : "You are not yet authenticated" }
      </div>

      {
        loggedIn 
        ? <div id="user-response">
          <div className="success">Verification Success</div>
          <div className="title-response">User info from Cotter:</div>
          <pre>{JSON.stringify(responsePayload, null, 4)}</pre>
        </div>
        : null
      }
    </div>
  );
}

export default IndexPage
```
<figcaption>your src/pages/index.js should be exactly like above</figcaption>

**ERROR: It's Ok.**

You will see an error indicating that you have not specified `styles.css`. Create a styles.css page under `src/pages/styles.css` and copy the code below:

```css
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
}

#user-info {
  padding: 10px;
  max-width: 350px;
  border-radius: 4px;
  background-color: #f5f5f5;
  margin-bottom: 10px;
}

#user-response {
  max-width: 500px;
  max-height: 400px;
}

.success {
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  text-align: center;
  color: hsl(171, 100%, 41%);
  margin-bottom: 10px;
}

pre {
  word-wrap: break-word;
  background-color: #2e2e2e;
  padding: 10px;
  border-radius: 4px;
  color: white;
  overflow: scroll;
}

.title-response {
  font-size: 13px;
  color: black;
}
```
<figcaption>src/pages/styles.css</figcaption>
# Integrating Cotter's Magic Link

**a. Install Cotter**

```
npm install cotter
```

> You may need to re run `gatsby develop` if you find any errors saying that you missed a few files inside `node_modules`. You can continue when if you don't see any errors.

**b. Build the login form**

Copy the code below

```react
{/* 1️⃣ TODO: Setup a div to contain the form */}
<div
  id="cotter-form-container"
  style={{ width: 300, height: 300 }}
></div>

```
<figcaption>src/pages/index.js</figcaption>

Then we import Cotter.

```react
// 2️⃣ TODO: Import Cotter
import Cotter from "cotter"; // 👈 Add Cotter here!
```
<figcaption>on the beginning of src/pages/index.js</figcaption>

Here we initialize Cotter, then show the form.

```react
// 3️⃣ TODO: Initialize Cotter and show the form
useEffect(() => {
    var cotter = new Cotter("<YOUR_API_KEY_ID>");
},[]);
```
<figcaption>src/pages/index.js</figcaption>

Replace `<YOUR_API_KEY_ID>` above with [your API Key ID](https://dev.cotter.app). Copy the code below to display the form.

```react
// 3️⃣ TODO: Initialize Cotter and show the form
useEffect(() => {
    var cotter = new Cotter("<YOUR_API_KEY_ID>");
+ cotter.signInWithLink().showEmailForm().then(payload => {
+ setResponsePayload(payload);
+ setLoggedIn(true);
+ });
}, []);
```
<figcaption>src/pages/index.js</figcaption>

To authenticate your users using a magic link via email, we will be using the `signInWithLink` function and `showEmailForm` as written above.

> You can send the magic link through SMS/WhatsApp as well by using `showPhoneForm`

Once a user is successfully authenticated, the `payload` will return information such as `oauth_token` , user's identifier (email or phone number), and Cotter's token.

> You can see that `showEmailForm` returns a Promise, that means you can simply handle any error by chaining a `catch` keyword after `then`.

## The Finish Line

![Cotter Magic Link Demo](https://dev-to-uploads.s3.amazonaws.com/i/uz862h705zmpr4ccsm3c.gif)<figcaption>Gatsby Email Link Authentication using Cotter</figcaption>

Done! You can now authenticate your users using a magic link without backend servers to store your users' credentials.

Find the [complete code here](https://github.com/cotter-code/guide-gatsby-magic-link).

## What's next?

You may have a backend service that serves your users personalized content. If so, then you will need to validate the payload on your backend server. Then, you can send your own authentication token to the client side, or simply use our `oauth_token` to validate your users from now on.

Learn more about [OAuth tokens returned from Cotter here](https://docs.cotter.app/v/0.1.0/getting-access-token/handling-authentication-with-cotter) to know more!

* * *

### Questions & Feedback

Come and talk to the founders of Cotter and other developers who are using Cotter on [Cotter's Slack Channel](https://join.slack.com/t/askcotter/shared_invite/zt-dxzf311g-5Mp3~odZNB2DwYaxIJ1dJA).

### 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](https://dev.cotter.app/) and [check out our documentation](https://docs.cotter.app/).

If you need help ping us on our Slack channel or email us at team@cotter.app.