How to Add LinkedIn Authentication to a Nuxt3 Application
Tags: appwrite, nuxt, typescript, linkedin
Published: 2022-09-19 14:39:06

Authentication is concerned with verifying identities. A typical example is logging into an application using an email or password, thus allowing the system to confirm if the entered credentials match the database's credentials.

[Appwrite](https://appwrite.io/docs?utm_source=hackmamba&utm_medium=blog&utm_campaign=hackmamba) is a self-hosted backend-as-a-service platform that provides developers with all of the core APIs required to build any application. [LinkedIn](https://www.linkedin.com/), on the other hand, is an employment-oriented service aimed at connecting career and business professionals.

This article will discuss how to authenticate a Nuxt3 application using Appwrite’s Linkedin OAuth provider.

## GitHub

Check out the complete source code [here](https://github.com/MoeRayo/nuxt3-linkedin-authentication).

## Prerequisites

Understanding this article requires the following:

- Installation of Node.js
- Basic knowledge of TypeScript
- Docker [installation](https://www.docker.com/get-started/)
- 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
- A LinkedIn account (Create an account [here](https://www.linkedin.com/signup))


## Creating a Nuxt.js Project

Use `npx create-nuxt-app <project-name>` to create a new Nuxt.js project. 
The process of scaffolding the project would provide a list of options, which should look like this:

![Nuxt create a new app commands](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3n31csvjmkppnfp7seg.png)

We are building our Nuxt3 application with TypeScript. As such, we will need to import the types for the Vue files. To do this, we will create a `vue-shim.d.ts` in our Nuxt3 application root folder and add the code block below to it:

```javascript
declare module "*.vue" {
  import Vue from 'vue'
  export default Vue
}
```

We can start our Nuxt3 application by running the following command:

```javascript
cd <project name>
npm run dev
```

Nuxt.js will, in turn, start a hot-reloading development environment that is accessible by default at `http://localhost:3000`.

## Installing Appwrite

To use Appwrite, we will install it in our project, like so:

```javascript
npm install nuxt-appwrite
```

### Configuring `nuxt.config` for Appwrite
We need to configure our Nuxt3 application in the `nuxt.config` file before we can use Appwrite.

To do this, we will register the Appwrite for global use in the `nuxt.config.js` file by adding `nuxt-appwrite` in the `modules` section:

```javascript
modules: [ 'nuxt-appwrite' ],
```

Appwrite also has a one-click to install DigitalOcean [droplet](https://marketplace.digitalocean.com/apps/appwrite?utm_source=hackmamba&utm_medium=blog&utm_campaign=hackmamba), allowing us to create an Appwrite droplet directly from DigitalOcean. 

## 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](https://appwrite.io/docs?utm_source=hackmamba&utm_medium=blog&utm_campaign=hackmamba) if we don’t have one. 
![Appwrite sign up page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/162iivbxz8cjewpcjr36.png)

Learn more about setting up Appwrite [here](https://dev.to/hackmamba/create-a-local-appwrite-instance-in-3-steps-19n9?utm_source=hackmamba&utm_medium=hackmamba). On the console, click on the **Create Project** button.

![Create project on Appwrite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/59tyysmhbnpshjdhudev.png)

Clicking on the **Create Project** will take us to an inner page where we can add our project name. We will add `appwrite_linkedin` as the name and click **Create**.


![inner create project page for appwrite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sigqnf5hzkggua4bnwok.png)


The project dashboard becomes visible on the console after project creation. We can access the inner page from the Settings tab at the top of the page. 

![Appwrite project dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6emxxq160bbmc2bdm9q.png)

The inner page allows us to copy the **Project ID** and **API Endpoint** for use in our Nuxt3 application.

![Appwrite settings page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9sh0eey51qjkjovhm6x9.png)


We will then proceed to create an `init.ts` file in our Nuxt.js application’s root directory to initialize the Appwrite Web SDK by adding the code block below:

```javascript
import { Appwrite } from 'appwrite';
export const sdk = new Appwrite();
sdk
  .setEndpoint('http://localhost/v1') // Replace this with your endpoint
  .setProject('***'); // Replace this with your ProjectID
```

### Activating LinkedIn OAuth provider on Appwrite

We will navigate to the **Users** section on the main menu, where we can access the **Settings** tab and select from the list of auth providers.

![Activating LinkedIn Oauth2 on Apprwite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0tr7m7z56tapbhhjpl1.png)

From the OAuth2 providers, we will look out for the LinkedIn provider to update its settings. 

![LinkedIn OAuth on Appwrite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3wb2a0uoosw0ip0scnrg.png)

Toggling the LinkedIn provider will bring to view the **App ID** and **App Secret** fields to be filled. We will fill these fields shortly, but we need to take note of the “LinkedIn redirect URL” provided as we need it for authentication on the LinkedIn dashboard.

![LinkedIn OAuth on Appwrite settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gonk21ddo6083g5duu4.png)

## Creating an App on LinkedIn

Appwrite's LinkedIn OAuth provider requires us to create an application on [LinkedIn](https://developer.linkedin.com/). Here we can click on the **Create app** button in the middle of the page.

![Creating app on GitHub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/im5t0kg8w7ymttr3q03e.png)

Clicking on the “Create app” button in the middle of the page will bring us to a new page below, where we can fill out the necessary information.


![Creating app on LinkedIn 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0m7tmknsv5oa3syix9d.png)

We will navigate to the **Auth** tab on the application dashboard when creating the application. We will copy the **Client ID** and **Client Secret** from our LinkedIn Auth dashboard. These keys can then be added to the empty fields shown in our Appwrite LinkedIn Oauth2 settings.


![Getting credentials from LinkedIn app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r63i4ed9c00z9rm9ob7u.png)

Just beneath the “application credentials,” we will add the **LinkedIn redirect URL** from the Appwrite application to the **Authorization callback URL** in the application, like so:


![Getting credentials from LinkedIn app2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62lmlnyc806rnia2ughv.png)

## Building Authentication in Nuxt.js

Our application will have two pages - the login page where authentication happens using the Appwrite LinkedIn provider and another where we display the user details.

### Creating the Login Page

The login page is the application’s entry point where users get authenticated. To build this, we will update the `pages/index.vue` with the code below:

```javascript
<template>
  <div class="bg-lightest-blue vh-100 pa3 tc">
    <h2 class="black ttc">LinkedIn authentication with Appwrite</h2>
    <div class="br3 bg-dark-blue ba near-white b--black-10 shadow-3 w-100 w-60-m w-30-l mw6 center mt5 ph4 pv4">
      <p class="f3">Click on this button to login</p>
        <button class="link dim br3 pv2 ph2 mb2 dib black fw6 bg-white ba b--navy pointer mt3 mt0-l inline-flex items-center" @click="loginWithLinkedin">
          <span class="f4 ml2 pr2">Login with Linkedin</span>
        </button>
    </div>
  </div>
</template>
<script lang="ts">
import {sdk} from '~/init'
export default {
  methods: {
    loginWithLinkedin: async function(){
      try {
        await sdk.account.createOAuth2Session('linkedin', 'http://localhost:3000/dashboard')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
```

In the code block, we achieved the following:

- The `<template>` tag contains the markup for displaying the login UI
- Imported the Apprwite SDK initialized in the `init.ts` file
- We created a `loginwithLinkedin` asynchronous function that uses the imported Appwrite SDK; within this function, we added the Appwrite `createOAuth2Session` method that received the following:
    - `linkedin`: this is the OAuth2 provider we would like users to use to sign in
    - A redirect URL where users are directed after successful authentication

### Creating the Dashboard Page
Next, we will create a page where users get redirected following a successful login. This page shows the user's name and email with an additional button that allows them to log out. To implement this, we will create a `pages/dashboard.vue` file and add the code below:

```javascript
<template>
  <div class="bg-lightest-blue vh-100 pa3 tc">
    <h2 class="tc">Linkedin authentication with Appwrite</h2>
    <div class="br3 bg-dark-blue ba near-white b--black-10 shadow-3 w-100 w-60-m w-30-l center mt5 ph4 pv4 mw6">
      <div class="f4 tl">
        <p class="yellow fw7">Name:</p>
        <p>{{name}}</p>
        <p class="mt4 yellow fw7">Email:</p>
        <p>{{email}}</p>
      </div>
      <button class="f4 link dim br3 pv2 ph3 mb2 dib black bg-white ba b--black pointer mt4 mt0-l inline-flex items-center" @click="logOutWithLinkedin">
        Log out
        </button>
    </div>
  </div>
</template>
<script>
import {sdk} from '~/init';
  export default {
    data(){
      return{
        namme: '',
        email: '',
        response: ''
      }
    },
    mounted: function(){
        this.getUserSession()
    },
    methods: {
      getUserSession: async function(){
        try {
          this.response = await sdk.account.get()
          if (this.response) {
            this.name = this.response.name,
            this.email = this.response.email 
          }
          
        } catch (error) {
          console.log(error)
        }
      },
      logOutWithLinkedin: async function(){
        try {
          await sdk.account.deleteSession('current')
          this.$router.push('/') 
        } catch (error) {
          console.log(error)
        }
      }
    }
  };
</script>
```

We achieved the following with the snippet above:

- Added the `<template>` tag for displaying the user information
- Imported the Appwrite SDK initialized in the `init.ts` file
- Updated the data property with `name`, `email`, and `response` to hold the user’s information
- Created a `getSession` function which gets executed when the application is mounted. This function fetched the logged-in user information for the current and updated the variables declared in the `data` property with the information
- Added the `logOutWithLinkedin` function, which is connected to Appwrite’s `deleteSession` method (the `logOutWithLinkedin` function logs the user out of the application and immediately routes the user to the home page)

At this stage, the application should look like the below:

![Final project overview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/52cfa9l52tmtwhj5dvh9.gif)

## Conclusion

This article explained how to add authentication to an application using Appwrite’s OAuth2 LinkedIn provider.

## Resources

Here are some resources that might be helpful:

- [Create a local Appwrite instance in 3 steps](https://dev.to/hackmamba/create-a-local-appwrite-instance-in-3-steps-19n9?utm_source=hackmamba&utm_medium=hackmamba) 
- [Appwrite account API documentation](https://appwrite.io/docs/client/account?sdk=web-default#accountCreateOAuth2Session?utm_source=hackmamba&utm_medium=blog&utm_campaign=auth0_auth0-authentication-vue)