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

note

If you get stuck while working through this guide, refer to the full example on GitHub.

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.

note

You can easily pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.


_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 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

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

Set up a Login route#

Let's set up an route to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords. Create an LoginPage with 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

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

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.component.ts

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

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.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 auomatically 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 deavice 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 bootstapping 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

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

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#