Home

Build a User Management App with Ionic Angular

This tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:

  • Supabase Database - a Postgres database for storing your user data and Row Level Security so data is protected and users can only access their own information.
  • Supabase Auth - users log in through magic links sent to their email (without having to set up passwords).
  • Supabase Storage - users can upload a profile photo.

Supabase User Management example

Project setup#

Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase and then creating a "schema" inside the database.

Create a project#

  1. Create a new project in the Supabase Dashboard.
  2. Enter your project details.
  3. Wait for the new database to launch.

Set up the database schema#

Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, or you can just copy/paste the SQL from below and run it yourself.

  1. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter.
  3. Click Run.

_10
supabase link --project-ref <project-id>
_10
# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>
_10
supabase db pull

Get the API Keys#

Now that you've created some database tables, you are ready to insert data using the auto-generated API. We just need to get the Project URL and anon key from the API settings.

  1. Go to the API Settings page in the Dashboard.
  2. Find your Project URL, anon, and service_role keys on this page.

Building the app#

Let's start building the Angular app from scratch.

Initialize an Ionic Angular app#

We can use the Ionic CLI to initialize an app called supabase-ionic-angular:


_10
npm install -g @ionic/cli
_10
ionic start supabase-ionic-angular blank --type angular
_10
cd supabase-ionic-angular

Then let's install the only additional dependency: supabase-js


_10
npm install @supabase/supabase-js

And finally, we want to save the environment variables in the src/environments/environment.ts file. All we need are the API URL and the anon key that you copied earlier. These variables will be exposed on the browser, and that's completely fine since we have Row Level Security enabled on our Database.

environment.ts

_10
export const environment = {
_10
production: false,
_10
supabaseUrl: 'YOUR_SUPABASE_URL',
_10
supabaseKey: 'YOUR_SUPABASE_KEY',
_10
}

Now that we have the API credentials in place, let's create a SupabaseService with ionic g s supabase to initialize the Supabase client and implement functions to communicate with the Supabase API.

src/app/supabase.service.ts

_77
import { Injectable } from '@angular/core'
_77
import { LoadingController, ToastController } from '@ionic/angular'
_77
import { AuthChangeEvent, createClient, Session, SupabaseClient } from '@supabase/supabase-js'
_77
import { environment } from '../environments/environment'
_77
_77
export interface Profile {
_77
username: string
_77
website: string
_77
avatar_url: string
_77
}
_77
_77
@Injectable({
_77
providedIn: 'root',
_77
})
_77
export class SupabaseService {
_77
private supabase: SupabaseClient
_77
_77
constructor(private loadingCtrl: LoadingController, private toastCtrl: ToastController) {
_77
this.supabase = createClient(environment.supabaseUrl, environment.supabaseKey)
_77
}
_77
_77
get user() {
_77
return this.supabase.auth.getUser().then(({ data }) => data?.user)
_77
}
_77
_77
get session() {
_77
return this.supabase.auth.getSession().then(({ data }) => data?.session)
_77
}
_77
_77
get profile() {
_77
return this.user
_77
.then((user) => user?.id)
_77
.then((id) =>
_77
this.supabase.from('profiles').select(`username, website, avatar_url`).eq('id', id).single()
_77
)
_77
}
_77
_77
authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) {
_77
return this.supabase.auth.onAuthStateChange(callback)
_77
}
_77
_77
signIn(email: string) {
_77
return this.supabase.auth.signInWithOtp({ email })
_77
}
_77
_77
signOut() {
_77
return this.supabase.auth.signOut()
_77
}
_77
_77
async updateProfile(profile: Profile) {
_77
const user = await this.user
_77
const update = {
_77
...profile,
_77
id: user?.id,
_77
updated_at: new Date(),
_77
}
_77
_77
return this.supabase.from('profiles').upsert(update)
_77
}
_77
_77
downLoadImage(path: string) {
_77
return this.supabase.storage.from('avatars').download(path)
_77
}
_77
_77
uploadAvatar(filePath: string, file: File) {
_77
return this.supabase.storage.from('avatars').upload(filePath, file)
_77
}
_77
_77
async createNotice(message: string) {
_77
const toast = await this.toastCtrl.create({ message, duration: 5000 })
_77
await toast.present()
_77
}
_77
_77
createLoader() {
_77
return this.loadingCtrl.create()
_77
}
_77
}

Set up a login route#

Let's set up a route to manage logins and signups. We'll use Magic Links so users can sign in with their email without using passwords. Create a LoginPage with the ionic g page login Ionic CLI command.

This guide will show the template inline, but the example app will have templateUrls

src/app/login/login.page.ts

_54
import { Component, OnInit } from '@angular/core'
_54
import { SupabaseService } from '../supabase.service'
_54
_54
@Component({
_54
selector: 'app-login',
_54
template: `
_54
<ion-header>
_54
<ion-toolbar>
_54
<ion-title>Login</ion-title>
_54
</ion-toolbar>
_54
</ion-header>
_54
_54
<ion-content>
_54
<div class="ion-padding">
_54
<h1>Supabase + Ionic Angular</h1>
_54
<p>Sign in via magic link with your email below</p>
_54
</div>
_54
<ion-list inset="true">
_54
<form (ngSubmit)="handleLogin($event)">
_54
<ion-item>
_54
<ion-label position="stacked">Email</ion-label>
_54
<ion-input [(ngModel)]="email" name="email" autocomplete type="email"></ion-input>
_54
</ion-item>
_54
<div class="ion-text-center">
_54
<ion-button type="submit" fill="clear">Login</ion-button>
_54
</div>
_54
</form>
_54
</ion-list>
_54
</ion-content>
_54
`,
_54
styleUrls: ['./login.page.scss'],
_54
})
_54
export class LoginPage {
_54
email = ''
_54
_54
constructor(private readonly supabase: SupabaseService) {}
_54
_54
async handleLogin(event: any) {
_54
event.preventDefault()
_54
const loader = await this.supabase.createLoader()
_54
await loader.present()
_54
try {
_54
const { error } = await this.supabase.signIn(this.email)
_54
if (error) {
_54
throw error
_54
}
_54
await loader.dismiss()
_54
await this.supabase.createNotice('Check your email for the login link!')
_54
} catch (error: any) {
_54
await loader.dismiss()
_54
await this.supabase.createNotice(error.error_description || error.message)
_54
}
_54
}
_54
}

Account page#

After a user is signed in, we can allow them to edit their profile details and manage their account. Create an AccountComponent with ionic g page account Ionic CLI command.

src/app/account.page.ts

_96
import { Component, OnInit } from '@angular/core'
_96
import { Router } from '@angular/router'
_96
import { Profile, SupabaseService } from '../supabase.service'
_96
_96
@Component({
_96
selector: 'app-account',
_96
template: `
_96
<ion-header>
_96
<ion-toolbar>
_96
<ion-title>Account</ion-title>
_96
</ion-toolbar>
_96
</ion-header>
_96
_96
<ion-content>
_96
<form>
_96
<ion-item>
_96
<ion-label position="stacked">Email</ion-label>
_96
<ion-input type="email" name="email" [(ngModel)]="email" readonly></ion-input>
_96
</ion-item>
_96
_96
<ion-item>
_96
<ion-label position="stacked">Name</ion-label>
_96
<ion-input type="text" name="username" [(ngModel)]="profile.username"></ion-input>
_96
</ion-item>
_96
_96
<ion-item>
_96
<ion-label position="stacked">Website</ion-label>
_96
<ion-input type="url" name="website" [(ngModel)]="profile.website"></ion-input>
_96
</ion-item>
_96
<div class="ion-text-center">
_96
<ion-button fill="clear" (click)="updateProfile()">Update Profile</ion-button>
_96
</div>
_96
</form>
_96
_96
<div class="ion-text-center">
_96
<ion-button fill="clear" (click)="signOut()">Log Out</ion-button>
_96
</div>
_96
</ion-content>
_96
`,
_96
styleUrls: ['./account.page.scss'],
_96
})
_96
export class AccountPage implements OnInit {
_96
profile: Profile = {
_96
username: '',
_96
avatar_url: '',
_96
website: '',
_96
}
_96
_96
email = ''
_96
_96
constructor(private readonly supabase: SupabaseService, private router: Router) {}
_96
ngOnInit() {
_96
this.getEmail()
_96
this.getProfile()
_96
}
_96
_96
async getEmail() {
_96
this.email = await this.supabase.user.then((user) => user?.email || '')
_96
}
_96
_96
async getProfile() {
_96
try {
_96
const { data: profile, error, status } = await this.supabase.profile
_96
if (error && status !== 406) {
_96
throw error
_96
}
_96
if (profile) {
_96
this.profile = profile
_96
}
_96
} catch (error: any) {
_96
alert(error.message)
_96
}
_96
}
_96
_96
async updateProfile(avatar_url: string = '') {
_96
const loader = await this.supabase.createLoader()
_96
await loader.present()
_96
try {
_96
const { error } = await this.supabase.updateProfile({ ...this.profile, avatar_url })
_96
if (error) {
_96
throw error
_96
}
_96
await loader.dismiss()
_96
await this.supabase.createNotice('Profile updated!')
_96
} catch (error: any) {
_96
await loader.dismiss()
_96
await this.supabase.createNotice(error.message)
_96
}
_96
}
_96
_96
async signOut() {
_96
console.log('testing?')
_96
await this.supabase.signOut()
_96
this.router.navigate(['/'], { replaceUrl: true })
_96
}
_96
}

Launch!#

Now that we have all the components in place, let's update AppComponent:

src/app/app.component.ts

_23
import { Component } from '@angular/core'
_23
import { Router } from '@angular/router'
_23
import { SupabaseService } from './supabase.service'
_23
_23
@Component({
_23
selector: 'app-root',
_23
template: `
_23
<ion-app>
_23
<ion-router-outlet></ion-router-outlet>
_23
</ion-app>
_23
`,
_23
styleUrls: ['app.component.scss'],
_23
})
_23
export class AppComponent {
_23
constructor(private supabase: SupabaseService, private router: Router) {
_23
this.supabase.authChanges((_, session) => {
_23
console.log(session)
_23
if (session?.user) {
_23
this.router.navigate(['/account'])
_23
}
_23
})
_23
}
_23
}

Then update the AppRoutingModule

src/app/app-routing.module.ts"

_23
import { NgModule } from '@angular/core'
_23
import { PreloadAllModules, RouterModule, Routes } from '@angular/router'
_23
_23
const routes: Routes = [
_23
{
_23
path: '/',
_23
loadChildren: () => import('./login/login.module').then((m) => m.LoginPageModule),
_23
},
_23
{
_23
path: 'account',
_23
loadChildren: () => import('./account/account.module').then((m) => m.AccountPageModule),
_23
},
_23
]
_23
_23
@NgModule({
_23
imports: [
_23
RouterModule.forRoot(routes, {
_23
preloadingStrategy: PreloadAllModules,
_23
}),
_23
],
_23
exports: [RouterModule],
_23
})
_23
export class AppRoutingModule {}

Once that's done, run this in a terminal window:


_10
ionic serve

And the browser will automatically open to show the app.

Supabase Angular

Bonus: Profile photos#

Every Supabase project is configured with Storage for managing large files like photos and videos.

Create an upload widget#

Let's create an avatar for the user so that they can upload a profile photo.

First, install two packages in order to interact with the user's camera.


_10
npm install @ionic/pwa-elements @capacitor/camera

CapacitorJS is a cross-platform native runtime from Ionic that enables web apps to be deployed through the app store and provides access to native device API.

Ionic PWA elements is a companion package that will polyfill certain browser APIs that provide no user interface with custom Ionic UI.

With those packages installed, we can update our main.ts to include an additional bootstrapping call for the Ionic PWA Elements.

src/main.ts

_15
import { enableProdMode } from '@angular/core'
_15
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'
_15
_15
import { AppModule } from './app/app.module'
_15
import { environment } from './environments/environment'
_15
_15
import { defineCustomElements } from '@ionic/pwa-elements/loader'
_15
defineCustomElements(window)
_15
_15
if (environment.production) {
_15
enableProdMode()
_15
}
_15
platformBrowserDynamic()
_15
.bootstrapModule(AppModule)
_15
.catch((err) => console.log(err))

Then create an AvatarComponent with this Ionic CLI command:


_10
ionic g component avatar --module=/src/app/account/account.module.ts --create-module

src/app/avatar.component.ts

_105
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
_105
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'
_105
import { SupabaseService } from '../supabase.service'
_105
import { Camera, CameraResultType } from '@capacitor/camera'
_105
import { addIcons } from 'ionicons'
_105
import { person } from 'ionicons/icons'
_105
@Component({
_105
selector: 'app-avatar',
_105
template: `
_105
<div class="avatar_wrapper" (click)="uploadAvatar()">
_105
<img *ngIf="_avatarUrl; else noAvatar" [src]="_avatarUrl" />
_105
<ng-template #noAvatar>
_105
<ion-icon name="person" class="no-avatar"></ion-icon>
_105
</ng-template>
_105
</div>
_105
`,
_105
style: [
_105
`
_105
:host {
_105
display: block;
_105
margin: auto;
_105
min-height: 150px;
_105
}
_105
:host .avatar_wrapper {
_105
margin: 16px auto 16px;
_105
border-radius: 50%;
_105
overflow: hidden;
_105
height: 150px;
_105
aspect-ratio: 1;
_105
background: var(--ion-color-step-50);
_105
border: thick solid var(--ion-color-step-200);
_105
}
_105
:host .avatar_wrapper:hover {
_105
cursor: pointer;
_105
}
_105
:host .avatar_wrapper ion-icon.no-avatar {
_105
width: 100%;
_105
height: 115%;
_105
}
_105
:host img {
_105
display: block;
_105
object-fit: cover;
_105
width: 100%;
_105
height: 100%;
_105
}
_105
`,
_105
],
_105
})
_105
export class AvatarComponent {
_105
_avatarUrl: SafeResourceUrl | undefined
_105
uploading = false
_105
_105
@Input()
_105
set avatarUrl(url: string | undefined) {
_105
if (url) {
_105
this.downloadImage(url)
_105
}
_105
}
_105
_105
@Output() upload = new EventEmitter<string>()
_105
_105
constructor(private readonly supabase: SupabaseService, private readonly dom: DomSanitizer) {
_105
addIcons({ person })
_105
}
_105
_105
async downloadImage(path: string) {
_105
try {
_105
const { data, error } = await this.supabase.downLoadImage(path)
_105
if (error) {
_105
throw error
_105
}
_105
this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(URL.createObjectURL(data!))
_105
} catch (error: any) {
_105
console.error('Error downloading image: ', error.message)
_105
}
_105
}
_105
_105
async uploadAvatar() {
_105
const loader = await this.supabase.createLoader()
_105
try {
_105
const photo = await Camera.getPhoto({
_105
resultType: CameraResultType.DataUrl,
_105
})
_105
_105
const file = await fetch(photo.dataUrl!)
_105
.then((res) => res.blob())
_105
.then((blob) => new File([blob], 'my-file', { type: `image/${photo.format}` }))
_105
_105
const fileName = `${Math.random()}-${new Date().getTime()}.${photo.format}`
_105
_105
await loader.present()
_105
const { error } = await this.supabase.uploadAvatar(fileName, file)
_105
_105
if (error) {
_105
throw error
_105
}
_105
_105
this.upload.emit(fileName)
_105
} catch (error: any) {
_105
this.supabase.createNotice(error.message)
_105
} finally {
_105
loader.dismiss()
_105
}
_105
}
_105
}

Add the new widget#

And then, we can add the widget on top of the AccountComponent HTML template:

src/app/account.component.ts

_15
template: `
_15
<ion-header>
_15
<ion-toolbar>
_15
<ion-title>Account</ion-title>
_15
</ion-toolbar>
_15
</ion-header>
_15
_15
<ion-content>
_15
<app-avatar
_15
[avatarUrl]="this.profile?.avatar_url"
_15
(upload)="updateProfile($event)"
_15
></app-avatar>
_15
_15
<!-- input fields -->
_15
`

Storage management#

If you upload additional profile photos, they'll accumulate in the avatars bucket because of their random names with only the latest being referenced from public.profiles and the older versions getting orphaned.

To automatically remove obsolete storage objects, extend the database triggers. Note that it is not sufficient to delete the objects from the storage.objects table because that would orphan and leak the actual storage objects in the S3 backend. Instead, invoke the storage API within Postgres via the http extension.

Enable the http extension for the extensions schema in the Dashboard. Then, define the following SQL functions in the SQL Editor to delete storage objects via the API:


_34
create or replace function delete_storage_object(bucket text, object text, out status int, out content text)
_34
returns record
_34
language 'plpgsql'
_34
security definer
_34
as $$
_34
declare
_34
project_url text := '<YOURPROJECTURL>';
_34
service_role_key text := '<YOURSERVICEROLEKEY>'; -- full access needed
_34
url text := project_url||'/storage/v1/object/'||bucket||'/'||object;
_34
begin
_34
select
_34
into status, content
_34
result.status::int, result.content::text
_34
FROM extensions.http((
_34
'DELETE',
_34
url,
_34
ARRAY[extensions.http_header('authorization','Bearer '||service_role_key)],
_34
NULL,
_34
NULL)::extensions.http_request) as result;
_34
end;
_34
$$;
_34
_34
create or replace function delete_avatar(avatar_url text, out status int, out content text)
_34
returns record
_34
language 'plpgsql'
_34
security definer
_34
as $$
_34
begin
_34
select
_34
into status, content
_34
result.status, result.content
_34
from public.delete_storage_object('avatars', avatar_url) as result;
_34
end;
_34
$$;

Next, add a trigger that removes any obsolete avatar whenever the profile is updated or deleted:


_32
create or replace function delete_old_avatar()
_32
returns trigger
_32
language 'plpgsql'
_32
security definer
_32
as $$
_32
declare
_32
status int;
_32
content text;
_32
avatar_name text;
_32
begin
_32
if coalesce(old.avatar_url, '') <> ''
_32
and (tg_op = 'DELETE' or (old.avatar_url <> coalesce(new.avatar_url, ''))) then
_32
-- extract avatar name
_32
avatar_name := old.avatar_url;
_32
select
_32
into status, content
_32
result.status, result.content
_32
from public.delete_avatar(avatar_name) as result;
_32
if status <> 200 then
_32
raise warning 'Could not delete avatar: % %', status, content;
_32
end if;
_32
end if;
_32
if tg_op = 'DELETE' then
_32
return old;
_32
end if;
_32
return new;
_32
end;
_32
$$;
_32
_32
create trigger before_profile_changes
_32
before update of avatar_url or delete on public.profiles
_32
for each row execute function public.delete_old_avatar();

Finally, delete the public.profile row before a user is deleted. If this step is omitted, you won't be able to delete users without first manually deleting their avatar image.


_14
create or replace function delete_old_profile()
_14
returns trigger
_14
language 'plpgsql'
_14
security definer
_14
as $$
_14
begin
_14
delete from public.profiles where id = old.id;
_14
return old;
_14
end;
_14
$$;
_14
_14
create trigger before_delete_user
_14
before delete on auth.users
_14
for each row execute function public.delete_old_profile();

At this stage, you have a fully functional application!

See also#