How to add Sign In with Notion to your webapp
Tags: javascript, webdev, react
Published: 2022-02-17 04:19:29

Hey everyone! This is kind of a continuation of [this tutorial](https://commotion.page/blog/how-to-create-a-form-app-with-the-notion-api) where we create a simple React/Express.js app that saves form responses directly to your Notion database. For this part, we’re picking up where we left off. How can we allow users to connect their Notion accounts so we can programmatically do things like fetch their data or saves responses to a Notion page in their workspace? It’s actually pretty easy!

**1. Make your integration into a public integration**

First, go to https://notion.so/my-integrations and select the integration you created in the last tutorial, Basic Form, or just create a new one.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/riolfpm8dmnmqbe5fi05.png)

Scroll down a bit and change your integration to a “Public integration.” This means this integration will allow other users to connect their Notion accounts to your integration rather than only your own account.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fegpp2egl889aef5hjky.png) 

In order to create a “Public integration”, you’ll need to fill in some info about your company. If you haven’t set up your own website, you can use your Notion page urls for things like your homepage or privacy policy site! Just whip up a Notion page, write some text, and plug it in here. Also, MAKE SURE YOU ADD “http://localhost:3000” TO REDIRECT URIs. This is very necessary.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zbn10w0rhvi4nyescc7j.png) 

Once you’ve submitted everything, scroll down to hit the save button. Once you do that, if you scroll to the top, you’ll now get an “OAuth client ID” and “OAuth client secret,” which you’ll need to use in your project.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/31m3j5wi2ej60u5oop2j.png) 

**2. Add a sign in link to your React app**

Alright, now that we got these, let’s start building. Let’s go back to the “form-tool” app that we created in the last tutorial (you can also just create a new react app with npx create-react-app form-tool ) and go to the App.js file and paste into it the below code. I’ll explain how this works in a bit.


```
// form-tool/src/App.js

import { useEffect, useState } from "react";

// The OAuth client ID from the integration page!
const oauth_client_id = "02e1f9d8-...";

function App() {
  const [dbs, setdbs] = useState([]);

  // When you open the app, this doesn't do anything, but after you sign into Notion, you'll be redirected back with a code at which point we call our backend.
  useEffect(() => {
    const params = new URL(window.document.location).searchParams;
    const code = params.get("code");
    if (!code) return;
    fetch(`http://localhost:3002/login/${code}`).then(async (resp) => {
      setdbs(await resp.json());
    });
  }, []);

  return (
    <div>
      <a
        style={{ display: "block" }}
        href={`https://api.notion.com/v1/oauth/authorize?client_id=${oauth_client_id}&response_type=code&owner=user`}
      >
        Connect to Notion
      </a>
      {dbs.map((db) => (
        <div
          style={{
            display: "inline-flex",
            whiteSpace: "pre",
            border: "1px solid black",
            marginBottom: 10,
          }}
        >
          {JSON.stringify(db, null, 2)}
        </div>
      ))}
    </div>
  );
}

export default App;
```

When you run npm run start, we get the following plain website.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/croeyq04uzped7pu50fr.png) 

When you click “Connect to Notion”, you should be brought over here to this sign in page.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yha9i3xl12qvl0smms4b.png) 

Once you fill everything out, we’re redirected back to our site and… nothing happens. That’s cause we need to update our backend as well. Before that, let’s explain what’s happening.

Essentially, we created a link to Notion’s site with the OAuth Client ID that allows you to sign into your Notion account. Once you select your workspace and the pages you want to give access to, you’ll be redirected to the url http://localhost:3000, which you should have put into the Redirect URI field in the integrations page. The caveat is now you’re given a secret code in the query parameter so the full URL is http://localhost:3000?code=SECRET_CODE… . With this secret code, you now can access the Notion user’s workspace.

So the flow goes: you open http://localhost:3000, you click on the click and go to https://www.notion.so/install-integration?…, and once you fill everything out, you’ll be sent to http://localhost:3000?code=CODE_VALUE…, with the code in hand. With this code, we’ll call our backend to start the real magic.

**3. Generate an access token and fetch user’s information with the Notion API**

Okay, now that we’ve logged in and have the code, now what do we with it? Well, we need to create a new endpoint in our backend. Let’s take the code that we just got from the frontend and convert it into an “access token” that we can actually use. With the token, we’ll return the user’s databases, but theoretically we can do anything we like with the Notion API. Go to your “form-tool-backend” Express.js project (you can also just create a new Express.js project), and go to the file app.js and paste in the code below. Make sure to update the variables with values in the integrations page that we retrieved earlier.

```
// form-tool-backend/app.js

const express = require("express");
const axios = require("axios");
const cors = require("cors");
const app = express();
const port = 3002;

// The OAuth client ID from the integration page!
const notionClientId = "02e1f9d8-...";

// The OAuth client secret from the integration page!
const notionClientSecret = "secret_...";

app.use(cors());
app.use(express.json());
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

app.get("/login/:code", async (req, res) => {
  const { code } = req.params;

  // Generate an access token with the code we got earlier and the client_id and client_secret we retrived earlier
  const resp = await axios({
    method: "POST",
    url: "https://api.notion.com/v1/oauth/token",
    auth: { username: notionClientId, password: notionClientSecret },
    headers: { "Content-Type": "application/json" },
    data: { code, grant_type: "authorization_code" },
  });

  // You want to save resp.data.workspace_id and resp.data.access_token if you want to make requests later with this Notion account (otherwise they'll need to reauthenticate)

  // Use the access token we just got to search the user's workspace for databases
  const { data } = await axios({
    method: "POST",
    url: "https://api.notion.com/v1/search",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${resp.data.access_token}`,
      "Notion-Version": "2021-08-16",
    },
    data: { filter: { property: "object", value: "database" } },
  });

  res.json(data?.results);
});
```

What’s happening? Well, the code we just got from the frontend, we send it to our backend, and with the code as well as our OAuth client ID and OAuth client secret, we can generate an “access_token” which is the real important thing. So we just used a code to then create our beautiful “access_token” which we can use with the Notion API to interact with the user’s workspace. The “access_token” is very powerful and thus should be hidden away in your backend only and should never be leaked. Save the “access_token” and “workspace_id” from the response we get from our first API call to the userID of the person that just signed in. Whenever you want to call the Notion API for them, retrieve the “access_token” so you don’t need them to sign in again to Notion.

With the “access_token”, we retrieve the user’s databases in the Notion workspace and return it to the frontend. We can do anything we like using this “access_token” that is outlined in the Notion API docs.

Once we add this endpoint to our backend, if we go back to our website and Connect to Notion, it will now fetch the database information and display it on your site.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9yy2fvp92my3ehcrank.png) 

Amazing! So what did we just do? Well, users can connect their Notion accounts, and then we can do things like fetch their data as well as make changes to their Notion workspace. So how could we use this to create a form app like Commotion? A user can connect their Notion account, and we’ll fetch their Notion database. With the database, we’ll generate a form, and when someone submits a response, we’ll take that data and add it to the user’s Notion database, all with the API. All we do is fetch the database here, but with the “access_token”, we can do much more.

We hope that this was a helpful tutorial! If you want forms for your Notion workspace but don’t have the time, definitely check us out at [Commotion.page](https://commotion.page)!