Create an Angular application

Run the following command to create a new Angular application:

npm install -g @angular/cli
ng new project-name --style=css --routing --standalone --defaults

This quickstarts examples are based on the Server Routing and App Engine APIs. Make sure while creating your angular project you accept (press ‘y’) the routing and App Engine.

Install @teamhanko/hanko-elements

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

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

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:4200/)

Setup your environments Variables

Create a new file environments.ts within your /src folder.

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

environments.ts
export const environment = {
  production: false,
  HANKO_API_URL: 'YOUR_HANKO_URL',
};

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

Create Hanko components

Let’s Create our HankoAuth and HankoProfile components. Run these commands in the terminal.

ng generate component HankoAuth --standalone
ng generate component HankoProfile --standalone

Also generate two pages with these commands, we will add the components in here.

ng generate component Home --standalone --type=page
ng generate component Dashboard --standalone --type=page

Hanko Auth

Now let’s set up the HankoAuth component.

For more information please refer to the Auth Component Page.

<hanko-auth (onSessionCreated)="redirectAfterLogin()" />

Now Import the HankoAuth component into the home page you previously made.

<!-- This is the selector from the hanko-auth.component.ts file -->
<app-hanko-auth/>

Hanko profile

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

For more information please refer to the Profile Component Page.

<hanko-profile/>

Now Import the HankoAuth component into the dashboard page you previously made.

<!-- This is the selector from the hanko-profile.component.ts file -->
<app-hanko-profile/>

Setting up routes

Remove everything in the app.component.html file and add a router outlet.

app.component.html
<router-outlet></router-outlet>

Now inport both pages into the app.routes.ts file and setup your routes.

app.routes.ts
import { Routes } from '@angular/router';

import { HomePage } from './home/home.page';
import { DashboardPage } from './dashboard/dashboard.page';

export const routes: Routes = [
  {
    path: '',
    component: HomePage,
  },
  {
    path: 'dashboard',
    component: DashboardPage,
  },
];

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👇

Use the command ng serve to start the server.

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.

Create the LogoutButton component with this command.

ng generate component LogoutButton --standalone

Now let’s set up the LogoutButton component.

<button (click)="logout()">Logout</button>

Let’s import this into our dashboard page.

<!-- This is the selector from the hanko-profile.component.ts file -->
<app-hanko-profile/>
<app-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 setup a guard that will check for authentication before the router activates the pages.

Create the authentication guard with this command.

ng generate guard auth --implements CanActivate

Then in auth.guard.ts, insert this code. This will grab the hanko session token and send it to the backend for validation.

import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';

export const authGuard: CanActivateFn = async (route, state) => {
  const router = inject(Router);
  const backendUrl = "http://localhost:5001";//change this to the url of your running hanko backend

  const sessionToken = isBrowser() ? getCookie('hanko') : null;
  if (!sessionToken) throw new Error('No session token found.');

  try {
    const response = await fetch(`${backendUrl}/validate`, {
      credentials: "include",
    });

    if (!response.ok) throw new Error('Session validation failed');

    return true;
  } catch (error) {
    console.error('AuthGuard error:', error);
    return router.parseUrl('/');// url to return the user to if they are not authenticated
  }
};

function getCookie(name: string): string | null {
  if (typeof document === 'undefined') return null;
  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
  return match ? match[2] : null;
}

function isBrowser(): boolean {
  return typeof window !== 'undefined' && typeof document !== 'undefined';
}

Add this authentication guard to the routes, in the app.routes.ts, which should only be accessible when the user is logged in.

app.routes.ts
import { Routes } from '@angular/router';

import { HomePage } from './home/home.page';
import { DashboardPage } from './dashboard/dashboard.page';

//Import the auth guard
import { authGuard } from './auth.guard';

export const routes: Routes = [
  {
    path: '',
    component: HomePage,
  },
  {
    path: 'dashboard',
    component: DashboardPage,
    canActivate: [authGuard]//secure the /dashboard path with the guard
  },
];

To verify that it works, logout on your app and go to /dashboard, you should get redirected back!

Getting user data

Let’s use the Hanko SDK to get user data to display on our dashboard page. For the user information we will use hanko.GetUser()

Lets update our dashboard page.

<app-hanko-profile/>
<app-logout-button/>

<h2>Email: {{email}}</h2>
<h2>Id: {{id}}</h2>

Try it yourself

Angular Example

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