Quickstart: Ionic Angular
Intro#
This example provides the steps to build a basic user management app. It includes:
- Supabase Database: a Postgres database for storing your user data.
- Supabase Auth: users can sign in with magic links (no passwords, only email).
- Supabase Storage: users can upload a photo.
- Row Level Security: data is protected so that individuals can only access their own data.
- Instant APIs: APIs will be automatically generated when you create your database tables.
By the end of this guide you'll have an app which allows users to login and update some basic profile details:
GitHub#
Should you get stuck while working through the guide, refer to this repo.
Project set up#
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#
- Go to app.supabase.com.
- Click on "New Project".
- Enter your project details.
- 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.
- Go to the SQL Editor page in the Dashboard.
- Click User Management Starter.
- Click Run.
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 URL and anon
key from the API settings.
- Go to the Settings page in the Dashboard.
- Click API in the sidebar.
- Find your API
URL
,anon
, andservice_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
:
npm install -g @ionic/cli ionic start supabase-ionic-angular blank --type angular cd supabase-ionic-angular
Then let's install the only additional dependency: supabase-js
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.ts1export const environment = {
2 production: false,
3 supabaseUrl: 'YOUR_SUPABASE_URL',
4 supabaseKey: 'YOUR_SUPABASE_KEY',
5}
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.ts1import { Injectable } from '@angular/core'
2import { LoadingController, ToastController } from '@ionic/angular'
3import { AuthChangeEvent, createClient, Session, SupabaseClient } from '@supabase/supabase-js'
4import { environment } from '../environments/environment'
5
6export interface Profile {
7 username: string
8 website: string
9 avatar_url: string
10}
11
12@Injectable({
13 providedIn: 'root',
14})
15export class SupabaseService {
16 private supabase: SupabaseClient
17
18 constructor(private loadingCtrl: LoadingController, private toastCtrl: ToastController) {
19 this.supabase = createClient(environment.supabaseUrl, environment.supabaseKey)
20 }
21
22 get user() {
23 return this.supabase.auth.user()
24 }
25
26 get session() {
27 return this.supabase.auth.session()
28 }
29
30 get profile() {
31 return this.supabase
32 .from('profiles')
33 .select(`username, website, avatar_url`)
34 .eq('id', this.user?.id)
35 .single()
36 }
37
38 authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) {
39 return this.supabase.auth.onAuthStateChange(callback)
40 }
41
42 signIn(email: string) {
43 return this.supabase.auth.signIn({ email })
44 }
45
46 signOut() {
47 return this.supabase.auth.signOut()
48 }
49
50 updateProfile(profile: Profile) {
51 const update = {
52 ...profile,
53 id: this.user?.id,
54 updated_at: new Date(),
55 }
56
57 return this.supabase.from('profiles').upsert(update, {
58 returning: 'minimal', // Don't return the value after inserting
59 })
60 }
61
62 downLoadImage(path: string) {
63 return this.supabase.storage.from('avatars').download(path)
64 }
65
66 uploadAvatar(filePath: string, file: File) {
67 return this.supabase.storage.from('avatars').upload(filePath, file)
68 }
69
70 async createNotice(message: string) {
71 const toast = await this.toastCtrl.create({ message, duration: 5000 })
72 await toast.present()
73 }
74
75 createLoader() {
76 return this.loadingCtrl.create()
77 }
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.ts1import { Component, OnInit } from '@angular/core'
2import { SupabaseService } from '../supabase.service'
3
4@Component({
5 selector: 'app-login',
6 template: `
7 <ion-header>
8 <ion-toolbar>
9 <ion-title>Login</ion-title>
10 </ion-toolbar>
11 </ion-header>
12
13 <ion-content>
14 <div class="ion-padding">
15 <h1>Supabase + Ionic Angular</h1>
16 <p>Sign in via magic link with your email below</p>
17 </div>
18 <ion-list inset="true">
19 <form (ngSubmit)="handleLogin($event)">
20 <ion-item>
21 <ion-label position="stacked">Email</ion-label>
22 <ion-input [(ngModel)]="email" name="email" autocomplete type="email"></ion-input>
23 </ion-item>
24 <div class="ion-text-center">
25 <ion-button type="submit" fill="clear">Login</ion-button>
26 </div>
27 </form>
28 </ion-list>
29 </ion-content>
30 `,
31 styleUrls: ['./login.page.scss'],
32})
33export class LoginPage implements OnInit {
34 email = ''
35 constructor(private readonly supabase: SupabaseService) {}
36
37 ngOnInit() {}
38 async handleLogin(event: any) {
39 event.preventDefault()
40 const loader = await this.supabase.createLoader()
41 await loader.present()
42 try {
43 await this.supabase.signIn(this.email)
44 await loader.dismiss()
45 await this.supabase.createNotice('Check your email for the login link!')
46 } catch (error) {
47 await loader.dismiss()
48 await this.supabase.createNotice(error.error_description || error.message)
49 }
50 }
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.ts1import { Component, OnInit } from '@angular/core'
2import { Router } from '@angular/router'
3import { Profile, SupabaseService } from '../supabase.service'
4
5@Component({
6 selector: 'app-account',
7 template: `
8 <ion-header>
9 <ion-toolbar>
10 <ion-title>Account</ion-title>
11 </ion-toolbar>
12 </ion-header>
13
14 <ion-content>
15 <form>
16 <ion-item>
17 <ion-label position="stacked">Email</ion-label>
18 <ion-input type="email" [value]="session?.user?.email"></ion-input>
19 </ion-item>
20
21 <ion-item>
22 <ion-label position="stacked">Name</ion-label>
23 <ion-input type="text" name="username" [(ngModel)]="profile.username"></ion-input>
24 </ion-item>
25
26 <ion-item>
27 <ion-label position="stacked">Website</ion-label>
28 <ion-input type="url" name="website" [(ngModel)]="profile.website"></ion-input>
29 </ion-item>
30 <div class="ion-text-center">
31 <ion-button fill="clear" (click)="updateProfile()">Update Profile</ion-button>
32 </div>
33 </form>
34
35 <div class="ion-text-center">
36 <ion-button fill="clear" (click)="signOut()">Log Out</ion-button>
37 </div>
38 </ion-content>
39 `,
40 styleUrls: ['./account.page.scss'],
41})
42export class AccountPage implements OnInit {
43 profile: Profile = {
44 username: '',
45 avatar_url: '',
46 website: '',
47 }
48
49 session = this.supabase.session
50
51 constructor(private readonly supabase: SupabaseService, private router: Router) {}
52 ngOnInit() {
53 this.getProfile()
54 }
55
56 async getProfile() {
57 try {
58 let { data: profile, error, status } = await this.supabase.profile
59 if (error && status !== 406) {
60 throw error
61 }
62 if (profile) {
63 this.profile = profile
64 }
65 } catch (error) {
66 alert(error.message)
67 }
68 }
69
70 async updateProfile(avatar_url: string = '') {
71 const loader = await this.supabase.createLoader()
72 await loader.present()
73 try {
74 await this.supabase.updateProfile({ ...this.profile, avatar_url })
75 await loader.dismiss()
76 await this.supabase.createNotice('Profile updated!')
77 } catch (error) {
78 await this.supabase.createNotice(error.message)
79 }
80 }
81
82 async signOut() {
83 console.log('testing?')
84 await this.supabase.signOut()
85 this.router.navigate(['/'], { replaceUrl: true })
86 }
87}
Launch!#
Now that we have all the components in place, let's update AppComponent:
src/app/app.component.ts1import { Component } from '@angular/core'
2import { Router } from '@angular/router'
3import { SupabaseService } from './supabase.service'
4
5@Component({
6 selector: 'app-root',
7 template: `
8 <ion-app>
9 <ion-router-outlet></ion-router-outlet>
10 </ion-app>
11 `,
12 styleUrls: ['app.component.scss'],
13})
14export class AppComponent {
15 constructor(private supabase: SupabaseService, private router: Router) {
16 this.supabase.authChanges((_, session) => {
17 console.log(session)
18 if (session?.user) {
19 this.router.navigate(['/account'])
20 }
21 })
22 }
23}
Then update the AppRoutingModule
src/app/app.ts"1import { NgModule } from '@angular/core'
2import { PreloadAllModules, RouterModule, Routes } from '@angular/router'
3
4const routes: Routes = [
5 {
6 path: '/',
7 loadChildren: () => import('./login/login.module').then((m) => m.LoginPageModule),
8 },
9 {
10 path: 'account',
11 loadChildren: () => import('./account/account.module').then((m) => m.AccountPageModule),
12 },
13]
14
15@NgModule({
16 imports: [
17 RouterModule.forRoot(routes, {
18 preloadingStrategy: PreloadAllModules,
19 }),
20 ],
21 exports: [RouterModule],
22})
23export class AppRoutingModule {}
Once that's done, run this in a terminal window:
ionic serve
And the browser will auomatically open to show the app.
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.
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.ts1import { enableProdMode } from '@angular/core'
2import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'
3
4import { AppModule } from './app/app.module'
5import { environment } from './environments/environment'
6
7import { defineCustomElements } from '@ionic/pwa-elements/loader'
8defineCustomElements(window)
9
10if (environment.production) {
11 enableProdMode()
12}
13platformBrowserDynamic()
14 .bootstrapModule(AppModule)
15 .catch((err) => console.log(err))
Then create an AvatarComponent with this Ionic CLI command:
ionic g component avatar --module=/src/app/account/account.module.ts --create-module
src/app/avatar.component.ts1import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
2import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'
3import { SupabaseService } from '../supabase.service'
4import { Camera, CameraResultType } from '@capacitor/camera'
5@Component({
6 selector: 'app-avatar',
7 template: `
8 <div class="avatar_wrapper" (click)="uploadAvatar()">
9 <img *ngIf="_avatarUrl; else noAvatar" [src]="_avatarUrl" />
10 <ng-template #noAvatar>
11 <ion-icon name="person" class="no-avatar"></ion-icon>
12 </ng-template>
13 </div>
14 `,
15 style: [
16 `
17 :host {
18 display: block;
19 margin: auto;
20 min-height: 150px;
21 }
22 :host .avatar_wrapper {
23 margin: 16px auto 16px;
24 border-radius: 50%;
25 overflow: hidden;
26 height: 150px;
27 aspect-ratio: 1;
28 background: var(--ion-color-step-50);
29 border: thick solid var(--ion-color-step-200);
30 }
31 :host .avatar_wrapper:hover {
32 cursor: pointer;
33 }
34 :host .avatar_wrapper ion-icon.no-avatar {
35 width: 100%;
36 height: 115%;
37 }
38 :host img {
39 display: block;
40 object-fit: cover;
41 width: 100%;
42 height: 100%;
43 }
44 `,
45 ],
46})
47export class AvatarComponent implements OnInit {
48 _avatarUrl: SafeResourceUrl | undefined
49 uploading = false
50
51 @Input()
52 set avatarUrl(url: string | undefined) {
53 if (url) {
54 this.downloadImage(url)
55 }
56 }
57
58 @Output() upload = new EventEmitter<string>()
59
60 constructor(private readonly supabase: SupabaseService, private readonly dom: DomSanitizer) {}
61
62 ngOnInit() {}
63
64 async downloadImage(path: string) {
65 try {
66 const { data } = await this.supabase.downLoadImage(path)
67 this._avatarUrl = this.dom.bypassSecurityTrustResourceUrl(URL.createObjectURL(data))
68 } catch (error) {
69 console.error('Error downloading image: ', error.message)
70 }
71 }
72
73 async uploadAvatar() {
74 const loader = await this.supabase.createLoader()
75 try {
76 const photo = await Camera.getPhoto({
77 resultType: CameraResultType.DataUrl,
78 })
79
80 const file = await fetch(photo.dataUrl)
81 .then((res) => res.blob())
82 .then((blob) => new File([blob], 'my-file', { type: `image/${photo.format}` }))
83
84 const fileName = `${Math.random()}-${new Date().getTime()}.${photo.format}`
85
86 await loader.present()
87 await this.supabase.uploadAvatar(fileName, file)
88
89 this.upload.emit(fileName)
90 } catch (error) {
91 this.supabase.createNotice(error.message)
92 } finally {
93 loader.dismiss()
94 }
95 }
96}
Add the new widget#
And then we can add the widget on top of the AccountComponent html template:
src/app/account.component.ts1template: ` 2<ion-header> 3 <ion-toolbar> 4 <ion-title>Account</ion-title> 5 </ion-toolbar> 6</ion-header> 7 8<ion-content> 9 <app-avatar 10 [avatarUrl]="this.profile?.avatar_url" 11 (upload)="updateProfile($event)" 12 ></app-avatar> 13 14<!-- input fields --> 15`
Next steps#
At this stage you have a fully functional application!
- Got a question? Ask here.
- Sign in: app.supabase.com