Phone Authentication with Appwrite and Vonage
Tags: appwrite, vonage, authentication, webdev
Published: 2022-11-08 15:52:32

**Appwrite 1.0** was recently announced and one of the many new updates it has brought is the addition of a **new phone authentication adapter**, **Vonage**! In this tutorial we’ll learn how to set up a Vonage account, configure it for use with Appwrite, and build a SvelteKit app to put it all together! Without further ado, let’s get started!

![Project Screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8t857bunbv2bk94s5brv.png)

> ### 🤔 New to Appwrite?

> [Appwrite](https://appwrite.io/) is an **open-source backend-as-a-service** that abstracts all the complexity of building a modern application by providing you with a set of REST and Realtime APIs for your core back-end needs. Appwrite takes the heavy lifting for developers and handles user authentication and authorization, databases, file storage, functions, webhooks, and much more!


## 📱Setting Up Vonage

The first step is to create a Vonage account. Head over to Vonage’s [website](https://www.vonage.com/) and [sign up](https://dashboard.nexmo.com/sign-up?icid=tryitfree_homepage_nexmodashbdfreetrialsignup_tile&utm_campaign=bizdirect&attribution_campaign=bizdirect&cjregion=429207&adobe_mc=MCMID%3D34270386780739068404296704713035591008%7CMCORGID%3DA8833BC75245AF9E0A490D4D%2540AdobeOrg%7CTS%3D1663266957) to use Vonage Communication APIs. On the Vonage API Dashboard, visit the **Numbers** tab on the sidebar and buy a [Virtual Number](https://developer.vonage.com/numbers/guides/number-management#rent-a-virtual-number).

![Vonage Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2w6a108su5dnuvhx6yvt.png)

This lets us avail a phone number that we can use to send messages from. On the dashboard, you’ll also find the API Key and API Secret. Keep these handy as you’ll need them in the next step.


## ⚙️ Installing Appwrite

Next, we need to get an Appwrite server up and running. You can either choose to [install it locally](https://appwrite.io/docs/installation#installWithDocker) on your system or deploy it on the cloud with one of our [one click setups](https://appwrite.io/docs/installation#one-click-setups).

![Appwrite Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q5cfj5inqi4fh2onrwyc.png)

TLDR; It only takes a single magic command! 😊

```sh
docker run -it --rm \
    --volume /var/run/docker.sock:/var/run/docker.sock \
    --volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
    --entrypoint="install" \
    appwrite/appwrite:1.2.1
```

This command installs Appwrite and creates an `appwrite` folder with `docker-compose.yml` and `.env` files. Once the installation is complete, head over to the `appwrite` folder.

We need to update two variables in the .env file namely `_APP_SMS_PROVIDER` and `_APP_SMS_FROM`. `_APP_SMS_FROM` is your Vonage phone number or brand name and `_APP_SMS_PROVIDER` is a DSN string that helps Appwrite connect to the [Vonage API](https://developer.vonage.com/api/sms#send-an-sms).

`_APP_SMS_PROVIDER` takes the following format

```
_APP_SMS_PROVIDER=phone://<API Key>:<API Secret>@vonage
```

`_APP_SMS_FROM` takes the following format

```
_APP_SMS_FROM=+14344251928
```

Once that is done, we need to restart the Appwrite server for the environment variables to take effect. Please note that this command needs to be executed from the `appwrite` folder that was created during installation.

```bash
docker compose up -d --force-recreate
```

Next, head over to localhost (or your public IP address) and create a new user account followed by a project with a name of your choosing.

Copy the `projectId` and the `endpoint` from the Settings page as we’ll need it for the web app we build in the next step!

## 🔮 Setting up Our SvelteKit Project

For this example, we’ll be using SvelteKit, but the concepts and code examples remain true for all web frameworks. First, we’ll need to create a new SvelteKit project and set up Tailwind CSS. The official [Tailwind installation guide](https://tailwindcss.com/docs/guides/sveltekit) is very handy for this purpose.

Instead of re-inventing the wheel here, I’d recommend you to complete the setup and return back to this tutorial.

Now, it’s time to install some of our dependencies. Head over to your project folder and run the following commands

```bash
npm i -D @zerodevx/svelte-toast
npm i appwrite
```

Next, add the following entries into your `.env` file. You might need to create this file if it does not exist already.

```
VITE_APPWRITE_ENDPOINT=<YOUR_APPWRITE_ENDPOINT>
VITE_APPWRITE_PROJECT_ID=<YOUR_APPWRITE_PROJECT_ID>
```

Don’t forget to replace the values with your own Appwrite `projectId` and `endpoint` that you obtained from the Dashboard earlier.

## 🔨 Setting up the Appwrite SDK

Next, let’s create our Appwrite service that will help abstract all the SDK calls to a single place. Create a new file `src/lib/appwrite.ts` and fill in the following contents

```ts
import { Client, Account } from 'appwrite';

const client = new Client();

client
    .setEndpoint(import.meta.env.VITE_APPWRITE_ENDPOINT)
    .setProject(import.meta.env.VITE_APPWRITE_PROJECT_ID);

const account = new Account(client);

export class AppwriteService {
    public static async getAccount(): Promise&lt;any> {
        return account.get();
    }

    public static async createAccount(email: string, password: string, name?: string): Promise<any> {
        return account.create('unique()', email, password, name);
    }

    public static async createEmailSession(email: string, password: string): Promise<any> {
        return account.createEmailSession(email, password);
    }

    public static async deleteSession(): Promise<any> {
        return account.deleteSession('current');
    }

    /** Phone Authentication endpoints */

    public static async createPhoneSession(number: string): Promise<any> {
        return account.createPhoneSession('unique()', number);
    }

    public static async updatePhoneSession(userId: string, secret: string): Promise<any> {
        return account.updatePhoneSession(userId, secret);
    }

    public static async updatePhone(number: string, password: string): Promise<any> {
        return account.updatePhone(number, password);
    }

    public static async createPhoneVerification(): Promise<any> {
        return account.createPhoneVerification();
    }

    public static async updatePhoneVerification(userId: string, secret: string): Promise<any> {
        return account.updatePhoneVerification(userId, secret);
    }

}
```

Here, we import the Appwrite SDK and initialize the Client and Account services. We also export an `AppwriteService` class with a lot of static methods that we can use across our app. The `appwrite.ts` file is all it takes to integrate Appwrite into the project. All the other files deal with the UI of the project and should be fairly straightforward to read and understand.

In order to keep this tutorial concise, we’ll just copy over the contents for all the other files from the [completed GitHub project](https://github.com/adityaoberai/appwrite-auth-demo). Once complete, we’re all ready to preview the project. Run the following command to run a local development server

```bash
npm run dev
``` 
 
That brings us to the end of this tutorial! I hope this guide helped you set up phone authentication in your web app and above all, I hope you enjoyed learning something new! I had a lot of fun trying out SvelteKit for this tutorial and I can’t wait to build some more apps!

## 📚 Resources

If you’re stuck at any point during the tutorial, feel free to reach out for help in our friendly discord channels run by humans! If you like what we do at Appwrite, don’t forget to drop us a tiny star on GitHub 😉 Here are some great resources to help you get started.


* [Appwrite Resource Showcase](https://github.com/appwrite/awesome-appwrite)
* [Svelte Documentation](https://svelte.dev/tutorial/basics)
* [Appwrite Documentation](https://appwrite.io/docs)
* [Appwrite's GitHub](https://github.com/appwrite/appwrite)