How to Authenticate a Next.js app with Okta
Tags: appwrite, nextjs, okta, authentication
Published: 2022-08-16 11:07:08

---
title: How to Authenticate a Next.js app with Okta
published: true
description: 
tags: Appwrite, Nextjs, Okta, Authentication
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kripuyjnawiesyfxcqi1.jpg
# Use a ratio of 100:42 for best results.
---
Ensuring that only authenticated users have access to specific parts of an application is an important aspect of web development.

In this article, we will learn how to authenticate a Next.js application using Appwrite’s Okta OAuth2 provider.

The source code is also available on [GitHub](https://github.com/nefejames/hackmamba-okta-next-auth).

Prerequisites
-------------

To get the most out of this project, the following are required:

-   Basic understanding of React and Next.js

-   Docker [installation](https://docs.docker.com/get-docker/)

-   An Appwrite instance; check out this [article](https://dev.to/hackmamba/create-a-local-appwrite-instance-in-3-steps-19n9?utm_source=hackmamba&utm_medium=hackmamba) on how to set up an instance

-   An Okta developer account (sign up [here](https://developer.okta.com/signup/))

Getting Started
---------------

Create a Next.js project by running the command below in our terminal:

```bash
npx create-next-app okta-auth-app
```

Next, navigate into the project directory.

```bash
cd okta-auth-app
```

Then, run the command below to start the application:

```bash
 npm run dev
```

Installing Appwrite
-------------------

[Appwrite](https://appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba-blog) is an open-source, end-to-end development platform that allows developers to build applications faster. Run the command below to install it:

```bash
npm i appwrite
```

Creating a New Appwrite Project
-------------------------------

To create a new project, start up the Appwrite instance on your machine and navigate to the specified hostname and port http://localhost:80. Next, we need to log in to our account or create an account if we don’t have one.

![Signup/login page](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655881360241_4-UbCF0g.png)

On the console, click the **Create Project** button, give the project a name, and then click **Create**.

![Create project](https://paper-attachments.dropbox.com/s_9C6F95223612512F2BFCBBAA719BAF62E5E51518F8EC1B3A16905A2D91336244_1650159125946_Screenshot+2022-04-17+at+02.28.39.png)

![Enter project name](https://paper-attachments.dropbox.com/s_BDB4B2E9DEBC947CF21789BC4224D1B5D1E6999B18844A1ABC22F2142E2E2A61_1653953612228_Screenshot+2022-05-30+at+15.00.51.png)

The project dashboard will appear on the console. Next, click on the **Settings** tab and copy the **Project ID** and **API Endpoint**.

![Appwrite Project ID and API Endpoint](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655881587894_project+appwrite.png)

Creating an Appwrite Instance in the Next.js App
------------------------------------------------

Create a `utils.js` file in the root of the application and in there, paste the code below:

```javascript
import { Appwrite } from "appwrite";
const appwrite = new Appwrite();
appwrite
  .setEndpoint("http://localhost/v1")
  .setProject("your-project-id");
export default appwrite;
```

We used the Appwrite **Project ID** and **API Endpoint** to set up the instance in our application.

Activating Okta Auth Method on Appwrite
---------------------------------------

Navigate to the **Users** menu, select the **Settings** tab, and enable the **Okta** OAuth2 provider:

![Okta providers](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655882165929_appwrite+Oauth+providers.png)

Upon enabling the Okta provider, we will be required to fill in the **App ID** and **App Secret**. We will fill them in shortly.

Copy Appwrite’s **callback URI** below, as we will need it to configure the Okta authentication later.

![Okta's OAuth settings](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655927856388_Screenshot_20.png)

Setting up an Okta Application
------------------------------

We need to set up a new integration on our Okta account. Go to the **Applications** page on the sidebar menu and click the **Create App Integration** button.

![Okta developer account page](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655882738295_Screenshot_11.png)

Select **OIDC - OpenID Connect** as the **Sign-in method** and **Web Application** as the **Application type**.

![Creating a new Okta app integration](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655882782830_Screenshot_12.png)

We need to configure the new app integration to work with Appwrite. Add the **callback URI** we copied earlier as one of the **Sign-in redirect URIs**, then save the application.

![New app integration](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655923982048_Screenshot_17.png)

We also need to copy the **Okta domain**, **Client ID**, and **Client Secret** and paste them into our Appwrite configuration. Then, click **Update**.

![Okta Client ID and Secret](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655882954151_Screenshot_14.png)

![Update Okta provider on Appwrite](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1655883031473_Screenshot_15.png)

Integrating Appwrite Authentication into Next.js
------------------------------------------------

The application will contain two pages; a page to log in and another page to show logged-in user details.

**Creating the login page** Update the `index.js` file inside the `pages` folder with the snippet below:

```javascript
import Head from "next/head";
import { Button, Center } from "@chakra-ui/react";
import appwrite from "utils";

export default function Home() {

  const loginWithOkta = async () => {
    try {
      await appwrite.account.createOAuth2Session(
        "okta",
        "http://localhost:3000/user"
      );
    } catch (error) {
      throw error;
    }
  };
  
  return (
    <Center>
      <Button onClick={loginWithOkta}>Login with Okta</Button>
    </Center>
  );
}
```

Here, we did the following:

-   Imported the required dependencies

-   Created a `loginWithOkta` asynchronous function that uses the Appwrite dk we initialized earlier to authenticate using Okta as the provider and `http://localhost:3000/user` as the URL it redirects to when the authentication is successful; we will create the user page in the next section

-   Passed the `loginWithOkta` function to the button’s `onClick` handler

**Creating the User Page** 
Create a `user.js` file in the `pages` directory and update it with the snippet below:

```javascript
import { Button, Center, Text, Heading, Stack } from "@chakra-ui/react";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import appwrite from "utils";

export default function User() {
  const [loggedInUser, setLoggedInUser] = useState(null);
  const router = useRouter();
  
  const getLoggedInUser = async () => {
    const data = (await appwrite) && appwrite.account.get();
    data
      .then((res) => setLoggedInUser(res))
      .catch((err) => {
        router.push("/");
        console.log(err);
      });
  };
  
  useEffect(() => {
    getLoggedInUser();
  }, []);
  
  const logOut = async () => {
    await appwrite.account.deleteSession("current");
    alert("logout successful");
    router.push("/");
  };
  
  return (
    loggedInUser && (
      <Center>
        <Stack>
          <Heading>You logged-in successfully</Heading>
          <Text>User: {loggedInUser.name}</Text>
          <p>Email: {loggedInUser.email}</p>
          <Button onClick={logOut} mt={20}>
            Logout
          </Button>
        </Stack>
      </Center>
    )
  );
}
```javascript

Here, we did the following:

-   Imported the required dependencies

-   Created state and route variables to manage logged-in user sessions and route accordingly

-   Created a `getLoggedInUser` function to get the logged-in user session and re-route to the login page if the session is empty and also called the function upon page load using the `useEffect` hook

-   Created a `logOut` function to log the user out and passed it to the button’s `onClick` handler

With that, we have successfully authenticated a Next.js app application with Okta.

![Demo](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1656544770916_ezgif.com-gif-maker2.gif)

Conclusion
----------

This post discussed how to authenticate a Next.js application using Appwrite’s Okta OAuth2 provider.

Resources
---------

These resources might be helpful:

-   [Set up Appwrite instance locally](https://dev.to/hackmamba/create-a-local-appwrite-instance-in-3-steps-19n9?utm_source=hackmamba&utm_medium=hackmamba) 

-   [Appwrite OAuth2 documentation](https://appwrite.io/docs/client/account?sdk=web-default#accountCreateOAuth2Session)

-   [Appwrite - Getting Started for Web](https://appwrite.io/docs/getting-started-for-web)