Create a Svelte application

To setup our Svelte Frontend we will use vite as a build tool.

Run the following command to create a new Vite Svelte application:

npm create vite@latest project-name -- --template svelte-ts

Install @teamhanko/hanko-elements

Once you’ve initialized your svelte app, installing hanko-elements provides you with access to the prebuilt components: hanko-auth and hanko-profile.

We will also install the svelte-routing package to handle routing and navigation.

cd project-name
npm install @teamhanko/hanko-elements svelte-routing

Setup your Hanko project

Go to the Hanko console and create a project for this application.

During creation make sure to input the URL you will be developing on as the APP URL. (Most likely http://localhost:5173/)

Add the Hanko API URL

Retrieve the API URL from the Hanko console and place it in your .env file.

.env
VITE_HANKO_API_URL=https://f4****-4802-49ad-8e0b-3d3****ab32.hanko.io

If you are self-hosting you need to provide the URL of your running Hanko backend.

Create Hanko components

Create a folder called components and create two files in it, HankoAuth.svelte and HankoProfile.svelte.

Hanko Auth

Now let’s set up the HankoAuth.svelte file to create a functioning login page.

For more information please refer to the Auth Component Page.

components/HankoAuth.svelte
<script>
  import { onMount } from "svelte";
	import { navigate } from 'svelte-routing';
  import { register } from "@teamhanko/hanko-elements";

  const hankoApi = import.meta.env.VITE_HANKO_API_URL;

  const redirectAfterLogin = () => {
    //User logged in
    navigate("/dashboard");//url to navigate to once logged in
  };

  onMount(async () => {
    register(hankoApi).catch((error) => {
      // handle error
    });
  });
</script>

<hanko-auth on:onSessionCreated={redirectAfterLogin} />

After you created the HankoAuth component, import and add it in any page.
Just like this.

pages/HomePage.svelte
<script>
    import HankoAuth from "../components/HankoAuth.svelte";
  </script>

  <HankoAuth/>

Hanko profile

After setting up the HankoAuth let’s set up the HankoProfile.svelte file to create a interface where users can.
manage their Email Addresses and credentials.

For more information please refer to the Profile Component Page.

components/HankoAuth.svelte
<script>
    import { register } from "@teamhanko/hanko-elements";
    import { onMount } from "svelte";

    const hankoApi = import.meta.env.VITE_HANKO_API_URL;
  
    onMount(async () => {
      register(hankoApi).catch((error) => {
        // handle error
      });
    });
</script>
  
<hanko-profile />

After you created the HankoProfile component, simply import it into any page.
In our case we created a dashboardPage.svelte file to show the HankoProfile as our Hanko Auth redirects to /dashboard.

pages/dashboardPage.svelte
<script>
	  import HankoProfile from './../components/HankoProfile.svelte';
</script>

<HankoProfile/>

Setup your routes

After you created the HomePage.svelte and DashboardPage.svelte you are able to import them into your svelte App.svelte. We will use svelte-router to setup the routes of your app.

App.svelte
<script>
  import { Router, Route } from "svelte-routing";
  import HomePage from "./pages/HomePage.svelte";
  import DashboardPage from "./pages/DashboardPage.svelte";
</script>

<Router>
    <Route path="/"><HomePage/></Route>
    <Route path="/dashboard"><DashboardPage/></Route>
</Router>

By now you should be able to go to / to see the <HankoAuth>, and to /dashboard to see the <HankoProfile>.

They should look something like this👇

Implement logout functionality

You can use @teamhanko/hanko-elements to easily log users out. Here we will make a logout button component that you can use anywhere.

For this QuickStart we will create a file at components/LogoutButton.svelte and insert the code below.

components/LogoutButton.svelte
<script>
    import { Hanko } from "@teamhanko/hanko-elements";
    import { navigate } from 'svelte-routing';

    const hankoApi = import.meta.env.VITE_HANKO_API_URL;
  
    const hanko = new Hanko(hankoApi);
    const logout = () => {
      hanko.logout().catch((error) => {
        //Handle Error
        console.log("Error during logging out : " + error);
      });
      navigate("/");//Url to redirect to
    };
  </script>
  
  <button on:click={logout}>Logout</button>

Customize component styles

You can customize the appearance of hanko-auth and hanko-profile components using CSS variables and parts. Refer to our customization guide.

Securing routes

To secure our routes we should validate the session token at the backend. Please refer to our backend guides.

Let’s set up a Protected route to do this for us. Create a new Svelte component at components/ProtectedRoute.svelte.

components/ProtectedRoute.svelte
<script>
    import { onMount } from "svelte";
    import { navigate } from "svelte-routing";

    async function validateSession() {
        try {
            const response = await fetch("http://localhost:5001/validate", {
            credentials: "include",
            });
            return response.ok;

        } catch (error) {
            return false;
        }
    }

    onMount(async () => {
        if(!await validateSession()){
            navigate("/");
        }
    })
</script>

<slot/>

Let’s import this ProtectedRoute.svelte to your App.svelte file.
To use the Protected route wrap your Dashboard in the Protected Route;

App.svelte
<script>
  import { Router, Route } from "svelte-routing";
  import HomePage from "./pages/HomePage.svelte";
  import DashboardPage from "./pages/DashboardPage.svelte";
  import ProtectedRoute from "./components/ProtectedRoute.svelte";
</script>

<Router>
    <Route path="/"><HomePage/></Route>
    <Route path="/dashboard">
      <ProtectedRoute>
        <DashboardPage/>
      </ProtectedRoute>
    </Route>
</Router>

Getting User and Session Data

Lets use the Hanko SDK to Get User Data to display on the dashboard. For the User Information we will use hanko.GetUser()

Lets update the dashboard page to log some of the information from the User And Session.

pages/DashboardPage.svelte
<script>
	  import HankoProfile from './../components/HankoProfile.svelte';
    import LogoutButton from './../components/LogoutButton.svelte';
    import { onMount } from 'svelte';
    const hankoApi = import.meta.env.VITE_HANKO_API_URL;

    let email = '';
    let id = '';

    async function fetchUserData() {
      const hanko = new Hanko(hankoApi);
      const _email = (await hanko.getUser()).emails?.[0]?.address;
      const _id = (await hanko.getUser()).user_id;
      return { email: _email, id: _id };
    }

    onMount(async () => {
      const data = await fetchUserData();
      email = data.email;
      id = data.id;
    });

</script>

<div>
    <HankoProfile/>
    <LogoutButton/>
    <h2>{email}</h2>
    <h2>{id}</h2>
</div>

Try it yourself

Svelte example

It uses Express.js for the backend, full source code available on our GitHub.