> ## Documentation Index
> Fetch the complete documentation index at: https://nocode-docs.zeroagent.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Email Password Authentication with HTML & JavaScript

> Learn how to build authentication with Zeromagic using HTML and JavaScript.

In this tutorial, we will be using **Email & Password** authentication system with HTML & Javascript Frontend. We will create a simple login form that will allow users to sign in to their account and redirect them to the dashboard page.

## Step 1 : Create the Login Page & Dashboard Page using HTML

Create two HTML files, `login.html` and `dashboard.html`. The `login.html` file will contain the login form, and the `dashboard.html` file will contain the dashboard page which will be redirect on successful login.

```html login.html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            background-color: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            width: 100%;
        }
        .container h2 {
            margin-bottom: 1rem;
            color: #333;
            text-align: center;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #555;
        }
        .form-group input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
        }
        .form-group input:focus {
            border-color: #007bff;
            outline: none;
        }
        .btn {
            width: 100%;
            padding: 0.75rem;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            font-size: 1rem;
            cursor: pointer;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .error {
            color: red;
            text-align: center;
            margin-bottom: 1rem;
        }
    </style>
    <script>
        async function login(event) {
            event.preventDefault();
            document.getElementById('error-message').textContent = '';

            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;

            try {
                const response = await fetch('{auth_base_url}/{auth_endpoint_path}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'APP-KEY' : '{your_app_key}'
                    },
                    body: JSON.stringify({ email, password })
                });

                if (response.ok) {
                    const data = await response.json();
                    sessionStorage.setItem('user_id', data.BODY.user_id);
                    sessionStorage.setItem('token', data.BODY.access_token);
                    window.location.href = 'dashboard.html';
                } else {
                    console.error('Error:', response);
                    document.getElementById('error-message').textContent = 'Login failed. Please check your credentials.';
                }
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('error-message').textContent = 'An error occurred. Please try again later.';
            }
        }
    </script>
</head>
<body>
    <div class="container">
        <h2>Login</h2>
        <div id="error-message" class="error"></div>
        <form onsubmit="login(event)">
            <div class="form-group">
                <label for="email">Email</label>
                <input type="email" id="email" required>
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" id="password" required>
            </div>
            <button type="submit" class="btn">Login</button>
        </form>
    </div>
</body>
</html>
```

```html dashboard.html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }
        .navbar {
            background-color: #007bff;
            padding: 1rem;
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .navbar h2 {
            margin: 0;
        }
        .btn-logout {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 5px;
            background-color: #ff4d4d;
            color: white;
            cursor: pointer;
        }
        .btn-logout:hover {
            background-color: #cc0000;
        }
        .content {
            padding: 2rem;
            text-align: center;
        }
        .welcome-message {
            font-size: 1.5rem;
            color: #333;
            margin-bottom: 2rem;
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const user = JSON.parse(sessionStorage.getItem('user_id'));
            const token = sessionStorage.getItem('token');

            if (!user || !token) {
                window.location.href = 'login.html';
            } else {
                document.getElementById('welcome-message').textContent = `Welcome, ${user.name}!`;
            }
        });

        function logout() {
            sessionStorage.removeItem('user');
            sessionStorage.removeItem('token');
            window.location.href = 'login.html';
        }
    </script>
</head>
<body>
    <div class="navbar">
        <h2>Dashboard</h2>
        <button class="btn-logout" onclick="logout()">Logout</button>
    </div>
    <div class="content">
        <div id="welcome-message" class="welcome-message"></div>
        <p>Login Successfull and user_id, access_token saved in the sessionStorage.</p>
        
        <p>Click on the logout button to clear the sessionStorage and redirect to the login page.</p> 
        
        <p>Here is your dashboard content. You can customize it to display user-specific information and actions.</p>

    </div>
</body>
</html>
```

## Step 2 : Setup Authentication in Zeromagic

1. Create and open a new `Project` in the console. Add a `Database` to the project. You can use the database spinned up by Zeromagic or connect your own database. Here we are using the cosmosdb database provided by Zeromagic. To add a database, click on the `Create Database` on the `Database` section button and add your database.

   <img src="https://mintcdn.com/zeromagiclabsprivatelimited/h_DeJnPWvd8dA9lO/assets/images/authentication-add-database.png?fit=max&auto=format&n=h_DeJnPWvd8dA9lO&q=85&s=a6e7391c60c7ef6988e7fcaa10d1ed1a" alt="Create Database" width="1849" height="885" data-path="assets/images/authentication-add-database.png" />

   > Refer here to know more about: [Creating Database on the platform](/datasources/quickstart)

2. Create a new environment and map the added database to the environment. Here we are using the `development` environment and `employees` database

   <img src="https://mintcdn.com/zeromagiclabsprivatelimited/h_DeJnPWvd8dA9lO/assets/images/authentication-add-environment.png?fit=max&auto=format&n=h_DeJnPWvd8dA9lO&q=85&s=9fc04a7dd437fdc9b3dbfac20ba7dcfb" alt="Create environment" width="1844" height="890" data-path="assets/images/authentication-add-environment.png" />

   > Refer here to know more about: [Creating Environments on the platform](/basics/environment)

3. Add the `Email & Password` authentication connection under Methods. Click `Add Connection` to create a new connection.

   <img src="https://mintcdn.com/zeromagiclabsprivatelimited/h_DeJnPWvd8dA9lO/assets/images/authentication-add-methods.png?fit=max&auto=format&n=h_DeJnPWvd8dA9lO&q=85&s=da784038f276ab5a3beeeb8a31de6f51" alt="Add Authentication" width="1863" height="921" data-path="assets/images/authentication-add-methods.png" />

   > Refer here to know more about: [Adding Authentication on the platform](/authentication/quickstart)

4. Now, go to `Environments` sections and select the environment you created. Copy the `Auth Endpoint URL` from the environment details. This is your authentication endpoint URL where you will be sending the APi requests. Your Auth endpoint URL looks similar to this:

   ```curl Auth Endpoint theme={null}
   http://authn.zeromagic.cloud/auth/86165f63f34e4be89809c2948c424a99/development/
   ```

5. Before making the APi request, let's **create a new user credentials** in the database for this example. You can **skip this step if your preferring to go with registering the user** and login with that user credentials. We do provide endpoints to create a new user also.

   <img src="https://mintcdn.com/zeromagiclabsprivatelimited/h_DeJnPWvd8dA9lO/assets/images/authentication-add-new-user.png?fit=max&auto=format&n=h_DeJnPWvd8dA9lO&q=85&s=adf8a4c8a567fcbe8fa55336acad0959" alt="Create User" width="1863" height="929" data-path="assets/images/authentication-add-new-user.png" />

   > Refer here to know more about: [Creating User on the platform](/authentication/users)

## Step 3 : Making the API Request

1. Replace the `{auth_base_url}/{auth_endpoint_path}` in the `login.html` file with the copied URL from the environment details and with the path to the email password login endpoint.
   Here the `{auth_base_url}` is `http://authn.zeromagic.cloud/auth/86165f63f34e4be89809c2948c424a99/development/` and `{auth_endpoint_path}` is `/email-password-login`.

   > Note: Replace the `auth_base_url` ith your actual URL. Refer to the [Authentication API Reference](/authentication/api/generalinfo) for more details on the API endpoints.

2. Replace the `{your_app_key}` with your actual `APP-KEY` in the headers of `login.html` file. You can find the `APP-ID` and `APP-KEY` in the `Manage -> Settings` section of your console.

   ```javascript login.html theme={null}
   async function login(event) {
       event.preventDefault();
       document.getElementById('error-message').textContent = '';
       const email = document.getElementById('email').value;
       const password = document.getElementById('password').value;

       try {
           //REPLACE HERE : `{auth_base_url}/{auth_endpoint_path}` with your auth base URL and api endpoint
           const response = await fetch('http://authn.zeromagic.cloud/auth/86165f63f34e4be89809c2948c424a99/development/email-password-login', {
               method: 'POST',
               headers: {
                   'Content-Type': 'application/json',
                   //REPLACE HERE : `{your_app_key}` with your APP-KEY
                   'APP-KEY': 'lwc66BSZmPilT7UnNhlut2QFfRYr82ErXMqCYsKhtFM'
               },
               body: JSON.stringify({ email, password })
           });

           if (response.ok) {
               const data = await response.json();
               sessionStorage.setItem('user_id', data.BODY.user_id);
               sessionStorage.setItem('token', data.BODY.access_token);
               window.location.href = 'dashboard.html';
           } else {
               console.error('Error:', response);
               document.getElementById('error-message').textContent = 'Login failed. Please check your credentials.';
           }
       } catch (error) {
           console.error('Error:', error);
           document.getElementById('error-message').textContent = 'An error occurred. Please try again later.';
       }
   }
   ```

## Step 4 : Run the Application and Login

1. Open the `login.html` file in your browser or with your preferred webserver. Enter the email and password of the user you created in the database and click on the `Login` button. Here login credentials users are
   ```curl Sample Credentails theme={null}
   email=genie@zeromagic.cloud
   password=genie#magic
   ```
2. If the login is successful, you will be redirected to the `dashboard.html` page. If the login fails, you will see an alert message.

## Summary

In this tutorial, you learned how to create a simple login form using HTML and JavaScript and authenticate users using the Zeromagic authentication API. This is a basic example to get you started with authentication in Zeromagic.

We provide more basic authentication methods and advanced method like social login. Feel free to explore the Authentication API Reference and reach out to us if you have any questions.

## Resource Links

* [Authentication API Reference](/authentication/api/generalinfo)
