How to Use Magic URL Login with Appwrite
Tags: webdev, javascript, beginners, tutorial
Published: 2022-01-29 12:00:49

Magic links allow you to log in without a password. Users don't have to enter any credentials to sign in; instead, they're sent a URL with an embedded token via email, or sometimes via SMS. When a user clicks the link for authentication, they are redirected back to the application or system, having successfully logged in as if they used a "magic" password, but without revealing any actual password.

Some organizations are moving away from password-based authentication to magic logins, depending on their risk appetite. If your users want access to their Slack inbox, Tumblr inbox, or apps and services within your company, magic login allows them to avoid remembering multiple passwords.

In this post, I’ll explore how does magic link works, its advantages,  and how to setup Magic URL Authentication to a Web Application using the [Appwrite](https://appwrite.io/) - [Web SDK](https://appwrite.io/docs/getting-started-for-web) 

## How does the magic link work?

![magic links.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1633582770350/mvpUnKFC9.png)

The magic login process consists of three steps:

1. First, a user enters their email address at your sign-in page.

2. Users will receive an e-mail with a magic link if it is a registered email address.

3. After opening the email, the user clicks the magic link to complete the sign-in process.

If the user chooses, the system can also send them a live link that they can use to authenticate themselves later on. The process is similar to one for changing a password, where the user receives a special link that will bypass his or her password and enable the user to create a new one. In order to establish magic login, app designers must come up with a solution for removing the password (and all associated resetting ceremonies) and instead of sending the user a one-time-use link.

A developer can either configure the link to stay valid for set periods of time or for the duration of a user session. When the user clicks the link in time, they are authenticated and a cookie is set so that they remain logged in throughout the session.

The magic link method works like password resets do, except the user doesn't have to remember a password or enter it to access their account. In this way, magic links simplify login procedures and provide an optimal user experience without imposing hardware requirements.

## How To Setup Magic Login in Appwrite

![logo.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1633585608498/sV0rM_RQw.png)

I'll walk you through adding Magic URL Authentication to a Web App using the [Appwrite](https://appwrite.io/) - [Web SDK](https://appwrite.io/docs/getting-started-for-web). The same can be done with our [Flutter SDK](https://appwrite.io/docs/getting-started-for-flutter) as well as our [Android SDK](https://appwrite.io/docs/getting-started-for-android).


Our first step will be to add our Web SDK to our project using NPM in the following manner:

```  
npm install appwrite --save

``` 
When you want to import Appwrite into a bundler (like [Rollup](https://rollupjs.org/guide/en/) or [Webpack](https://webpack.js.org/)), do the following:

``` 
import { Appwrite } from "appwrite";

``` 
In order to use an Appwrite service with a CDN (content delivery network), you must add the following script to your HTML file:

```  
<script src="https://cdn.jsdelivr.net/npm/appwrite"></script>

``` 
As the next step, you need to initialize the SDK with your project ID, which you will find in your project settings:

``` 
// Init your Web SDK
const appwrite = new Appwrite();

appwrite
    .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint
    .setProject('455x34dfkj') // Your Appwrite Project ID
;

``` 
## How To Create A Magic URL IN Appwrite

When your SDK has been set up, access the Account service and call the [createMagicURLSession()](https://appwrite.io/docs/client/account?sdk=web#accountCreateMagicURLSession) method. As arguments, the method accepts an email address and a redirect URL.   

```  
// Initiate the Magic URL login
appwrite.account.createMagicURLSession('name@example.com', 'http://localhost/')
    .then(response => {
        console.log(response); // Success
    }, error => {
        console.log(error); // Failure
    });

``` 
The user is emailed the URL containing the secret key if the [createMagicURLSession()](https://appwrite.io/docs/client/account?sdk=web#accountCreateMagicURLSession) method is completed without error. Clicking on the link will redirect the user to the link URL you provided, with userId and secret key attached to it in the URL query string. After 1 hour this link will no longer be valid. By default, if the provided e-mail address does not already belong to any user, a new one will be created.  

 ## How To Login with a Magic URL in Appwrite

We can now complete the authentication process by handling the redirect from the URL in the e-mail as the user is now in a position to begin it.

With the query strings for the secret and userId values from the URL, call the [updateMagicURLSession()](https://appwrite.io/docs/client/account?sdk=web#accountUpdateMagicURLSession) method.

> To avoid [Redirect Attacks](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), only the domains you specified when adding your platforms via the console will work as redirect URLs.

```  
const urlParams = new URLSearchParams(window.location.search);
const userId = urlParams.get('userId');
const secret = urlParams.get('secret');

let promise = appwrite.account.updateMagicURLSession(userId, secret);

promise.then(function (response) {
    console.log(response); // Success
}, function (error) {
    console.log(error); // Failure
});

``` 
A successful [updateMagicURLSession()](https://appwrite.io/docs/client/account?sdk=web#accountUpdateMagicURLSession) will result in the user being logged in. Once a link has been used, it cannot be used again.  

## Benefits of using magic links

Implementing magic links has many benefits for organizations. The following are some of these benefits:

- **Easy authentication deployment and use:** Due to the near-identical flow of magic links and password resets, implementing them requires only small changes in code without incurring significant additional costs.

- **Seamless onboarding:** A simple magic link allows users to register for an app with their email address, making it simple and inviting to use.

- **Reduced login troubleshooting:** With magic links replacing passwords, organizations experience lower administrative costs. As a result, security alerts and new password requests will become less of a hassle.

- **High usability on a range of devices:** Users can authenticate with magic links on any device that can access email, so they're equally applicable across smartphones, tablets, laptops, and desktops. Clicking on the link will authenticate the user on the device they're using. Users are naturally accustomed to opening emails on the device they're working on at the time, so this shouldn't cause any friction.



If you want to keep your customers' accounts secure without compromising a simple user experience, magic links are a great option. Is magic links the best user authentication option for your application? The answer likely depends on what the application does. It may not be a wise choice to use magic links when handling sensitive financial or health care data. If your specialty is entertainment and online shopping, you're probably all set!

Want to give magic links a try? With [Appwrite](https://appwrite.io/), magic links are free and easy to set you up. If you have any queries regarding it you can hop in the [Appwrite Discord Server](https://discord.gg/rMmjTs6wVw) and get your queries resolved.

## References:

- [Appwrite Discord](https://discord.gg/rMmjTs6wVw)

- [Appwrite Documentation](https://appwrite.io/docs)

- [Appwrite Homepage](https://appwrite.io/)

I hope that this article helped you to see how easy it is in Appwrite to add magic login methods for your customers. So what are you waiting for go and use Appwrite in your projects

Happy Appwriting ♥

> You can now extend your support by buying me a Coffee.😊👇

<a href="https://www.buymeacoffee.com/muthuannamalai" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>

Thanks for Reading 😊