{"id":4109,"date":"2023-11-04T23:14:03","date_gmt":"2023-11-04T23:14:03","guid":{"rendered":"http:\/\/localhost:10003\/how-to-build-a-social-media-app-with-ionic-and-firebase\/"},"modified":"2023-11-05T05:48:01","modified_gmt":"2023-11-05T05:48:01","slug":"how-to-build-a-social-media-app-with-ionic-and-firebase","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-build-a-social-media-app-with-ionic-and-firebase\/","title":{"rendered":"How to Build a Social Media App with Ionic and Firebase"},"content":{"rendered":"
In this tutorial, we’ll walk through the steps to build a social media app using Ionic framework and Firebase backend. We’ll cover the essential features like user authentication, posting, liking, and commenting on posts, as well as displaying and updating user profiles. By the end of this tutorial, you’ll have a fully functional social media app that can be compiled for both iOS and Android devices.<\/p>\n
Before we start, make sure you have the following software installed on your system:<\/p>\n
npm install -g ionic<\/code><\/li>\n- Firebase CLI:
npm install -g firebase-tools<\/code><\/li>\n<\/ul>\nYou’ll also need a Firebase project. If you don’t have one, sign in to the Firebase console (https:\/\/console.firebase.google.com<\/a>), create a new project, and note down the project ID and API keys.<\/p>\nSetting up the Ionic Project<\/h2>\n
Let’s start by setting up our Ionic project. Open a terminal or command prompt and run the following commands:<\/p>\n
ionic start social-media-app blank --type=angular\ncd social-media-app\n<\/code><\/pre>\nNext, add the iOS and Android platforms:<\/p>\n
ionic capacitor add ios\nionic capacitor add android\n<\/code><\/pre>\nUser Authentication with Firebase<\/h2>\n
To allow users to sign up and sign in to our app, we’ll use Firebase Authentication. Run the following command to install the Firebase SDK:<\/p>\n
npm install firebase @angular\/fire\n<\/code><\/pre>\nNext, open the src\/environments\/environment.ts<\/code> file and add the Firebase configuration. Replace YOUR_FIREBASE_CONFIG<\/code> with your actual Firebase project configuration:<\/p>\nexport const environment = {\n production: false,\n firebase: {\n apiKey: \"YOUR_FIREBASE_API_KEY\",\n authDomain: \"YOUR_FIREBASE_AUTH_DOMAIN\",\n projectId: \"YOUR_FIREBASE_PROJECT_ID\",\n storageBucket: \"YOUR_FIREBASE_STORAGE_BUCKET\",\n messagingSenderId: \"YOUR_FIREBASE_MESSAGING_SENDER_ID\",\n appId: \"YOUR_FIREBASE_APP_ID\"\n }\n};\n<\/code><\/pre>\nNow, open the src\/app\/app.module.ts<\/code> file and import the following modules:<\/p>\nimport { AngularFireModule } from '@angular\/fire';\nimport { AngularFireAuthModule } from '@angular\/fire\/auth';\nimport { environment } from '..\/environments\/environment';\n<\/code><\/pre>\nThen, add AngularFireModule.initializeApp(environment.firebase)<\/code> and AngularFireAuthModule<\/code> to the imports section of the @NgModule<\/code> decorator.<\/p>\nThe final app.module.ts<\/code> file should look like this:<\/p>\nimport { NgModule } from '@angular\/core';\nimport { BrowserModule } from '@angular\/platform-browser';\nimport { IonicModule } from '@ionic\/angular';\n\nimport { AppRoutingModule } from '.\/app-routing.module';\nimport { AppComponent } from '.\/app.component';\n\nimport { AngularFireModule } from '@angular\/fire';\nimport { AngularFireAuthModule } from '@angular\/fire\/auth';\nimport { environment } from '..\/environments\/environment';\n\n@NgModule({\n declarations: [AppComponent],\n entryComponents: [],\n imports: [\n BrowserModule,\n IonicModule.forRoot(),\n AppRoutingModule,\n AngularFireModule.initializeApp(environment.firebase),\n AngularFireAuthModule,\n ],\n providers: [],\n bootstrap: [AppComponent],\n})\nexport class AppModule {}\n<\/code><\/pre>\nCreating the Authentication Service<\/h2>\n
Let’s create a service to handle user authentication. Run the following command to generate a new service:<\/p>\n
ionic generate service services\/authentication\n<\/code><\/pre>\nOpen the newly created src\/app\/services\/authentication.service.ts<\/code> file and replace the contents with the following code:<\/p>\nimport { Injectable } from \"@angular\/core\";\nimport { AngularFireAuth } from \"@angular\/fire\/auth\";\n\n@Injectable({\n providedIn: \"root\"\n})\nexport class AuthenticationService {\n constructor(private afAuth: AngularFireAuth) {}\n\n signup(email: string, password: string) {\n return this.afAuth.createUserWithEmailAndPassword(email, password);\n }\n\n login(email: string, password: string) {\n return this.afAuth.signInWithEmailAndPassword(email, password);\n }\n\n logout() {\n return this.afAuth.signOut();\n }\n\n getCurrentUser() {\n return this.afAuth.user;\n }\n}\n<\/code><\/pre>\nThis service provides methods for signing up, logging in, logging out, and getting the current user.<\/p>\n
Implementing the Authentication Flow<\/h2>\n
Now, let’s add the authentication flow to our app.<\/p>\n
Open the src\/app\/app.component.html<\/code> file and replace its contents with the following code:<\/p>\n<ion-app>\n <ion-router-outlet><\/ion-router-outlet>\n<\/ion-app>\n<\/code><\/pre>\nNext, create a new file src\/app\/pages\/login\/login.page.html<\/code> and add the following code:<\/p>\n<ion-header>\n <ion-toolbar>\n <ion-title>Login<\/ion-title>\n <\/ion-toolbar>\n<\/ion-header>\n\n<ion-content>\n <ion-grid>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-label>Login to your account<\/ion-label>\n <\/ion-col>\n <\/ion-row>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-item>\n <ion-label position=\"floating\">Email<\/ion-label>\n <ion-input [(ngModel)]=\"email\" type=\"email\"><\/ion-input>\n <\/ion-item>\n <\/ion-col>\n <\/ion-row>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-item>\n <ion-label position=\"floating\">Password<\/ion-label>\n <ion-input [(ngModel)]=\"password\" type=\"password\"><\/ion-input>\n <\/ion-item>\n <\/ion-col>\n <\/ion-row>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-button expand=\"full\" (click)=\"login()\">Login<\/ion-button>\n <\/ion-col>\n <\/ion-row>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-button expand=\"full\" color=\"medium\" (click)=\"goToSignup()\">Don't have an account? Sign up<\/ion-button>\n <\/ion-col>\n <\/ion-row>\n <\/ion-grid>\n<\/ion-content>\n<\/code><\/pre>\nCreate a new file src\/app\/pages\/login\/login.page.ts<\/code> and add the following code:<\/p>\nimport { Component, OnInit } from \"@angular\/core\";\nimport { Router } from \"@angular\/router\";\nimport { AuthenticationService } from \"..\/..\/services\/authentication.service\";\n\n@Component({\n selector: \"app-login\",\n templateUrl: \".\/login.page.html\",\n styleUrls: [\".\/login.page.scss\"],\n})\nexport class LoginPage implements OnInit {\n email: string;\n password: string;\n\n constructor(private authService: AuthenticationService, private router: Router) {}\n\n ngOnInit() {}\n\n login() {\n this.authService.login(this.email, this.password).then(() => {\n this.router.navigateByUrl(\"\/home\");\n });\n }\n\n goToSignup() {\n this.router.navigateByUrl(\"\/signup\");\n }\n}\n<\/code><\/pre>\nSimilarly, create a new file src\/app\/pages\/signup\/signup.page.html<\/code> with the following content:<\/p>\n<ion-header>\n <ion-toolbar>\n <ion-title>Sign Up<\/ion-title>\n <\/ion-toolbar>\n<\/ion-header>\n\n<ion-content>\n <ion-grid>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-label>Create an account<\/ion-label>\n <\/ion-col>\n <\/ion-row>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-item>\n <ion-label position=\"floating\">Email<\/ion-label>\n <ion-input [(ngModel)]=\"email\" type=\"email\"><\/ion-input>\n <\/ion-item>\n <\/ion-col>\n <\/ion-row>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-item>\n <ion-label position=\"floating\">Password<\/ion-label>\n <ion-input [(ngModel)]=\"password\" type=\"password\"><\/ion-input>\n <\/ion-item>\n <\/ion-col>\n <\/ion-row>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-button expand=\"full\" (click)=\"signup()\">Sign Up<\/ion-button>\n <\/ion-col>\n <\/ion-row>\n <ion-row>\n <ion-col size=\"12\" offset=\"0\" text-center>\n <ion-button expand=\"full\" color=\"medium\" (click)=\"goToLogin()\">Already have an account? Login<\/ion-button>\n <\/ion-col>\n <\/ion-row>\n <\/ion-grid>\n<\/ion-content>\n<\/code><\/pre>\nIn the src\/app\/pages\/signup\/signup.page.ts<\/code> file, add the following code:<\/p>\nimport { Component, OnInit } from \"@angular\/core\";\nimport { Router } from \"@angular\/router\";\nimport { AuthenticationService } from \"..\/..\/services\/authentication.service\";\n\n@Component({\n selector: \"app-signup\",\n templateUrl: \".\/signup.page.html\",\n styleUrls: [\".\/signup.page.scss\"],\n})\nexport class SignupPage implements OnInit {\n email: string;\n password: string;\n\n constructor(private authService: AuthenticationService, private router: Router) {}\n\n ngOnInit() {}\n\n signup() {\n this.authService.signup(this.email, this.password).then(() => {\n this.router.navigateByUrl(\"\/home\");\n });\n }\n\n goToLogin() {\n this.router.navigateByUrl(\"\/login\");\n }\n}\n<\/code><\/pre>\nNow, let’s update the src\/app\/app-routing.module.ts<\/code> file to include the authentication routes. Replace its contents with:<\/p>\nimport { NgModule } from \"@angular\/core\";\nimport { RouterModule, Routes } from \"@angular\/router\";\nimport { LoginPage } from \".\/pages\/login\/login.page\";\nimport { SignupPage } from \".\/pages\/signup\/signup.page\";\n\nconst routes: Routes = [\n { path: \"\", redirectTo: \"login\", pathMatch: \"full\" },\n { path: \"login\", component: LoginPage },\n { path: \"signup\", component: SignupPage },\n];\n\n@NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule],\n})\nexport class AppRoutingModule {}\n<\/code><\/pre>\nLet’s update the src\/app\/app.component.ts<\/code> file to check if the user is logged in and route to the correct page. Replace its code with:<\/p>\nimport { Component } from \"@angular\/core\";\nimport { Router } from \"@angular\/router\";\nimport { AuthenticationService } from \".\/services\/authentication.service\";\nimport { User } from \"firebase\/app\";\n\n@Component({\n selector: \"app-root\",\n templateUrl: \"app.component.html\",\n styleUrls: [\"app.component.scss\"],\n})\nexport class AppComponent {\n currentUser: User;\n\n constructor(private authService: AuthenticationService, private router: Router) {\n this.authService.getCurrentUser().subscribe((user) => {\n this.currentUser = user;\n if (this.currentUser) {\n this.router.navigateByUrl(\"\/home\");\n } else {\n this.router.navigateByUrl(\"\/login\");\n }\n });\n }\n}\n<\/code><\/pre>\nNow, if you run the app using ionic serve<\/code>, you should see the login page. You can sign up with a new account or log in with an existing account to proceed.<\/p>\nBuilding the Feed Page<\/h2>\n
Now that we have the authentication flow, let’s create the home page where users can see and interact with the feed.<\/p>\n
First, update the src\/app\/app-routing.module.ts<\/code> file to include a new route:<\/p>\nimport { NgModule } from \"@angular\/core\";\nimport { RouterModule, Routes } from \"@angular\/router\";\nimport { LoginPage } from \".\/pages\/login\/login.page\";\nimport { SignupPage } from \".\/pages\/signup\/signup.page\";\nimport { HomePage } from \".\/pages\/home\/home.page\";\n\nconst routes: Routes = [\n { path: \"\", redirectTo: \"login\", pathMatch: \"full\" },\n { path: \"login\", component: LoginPage },\n { path: \"signup\", component: SignupPage },\n { path: \"home\", component: HomePage },\n];\n\n@NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule],\n})\nexport class AppRoutingModule {}\n<\/code><\/pre>\nNext, generate a new page for the home feed:<\/p>\n
ionic generate page pages\/home\n<\/code><\/pre>\nOpen the src\/app\/pages\/home\/home.page.html<\/code> file and replace the contents with the following code:<\/p>\n<ion-header>\n <ion-toolbar>\n <ion-title>Welcome to the Feed<\/ion-title>\n <\/ion-toolbar>\n<\/ion-header>\n\n<ion-content>\n <ion-button (click)=\"logout()\">Logout<\/ion-button>\n<\/ion-content>\n<\/code><\/pre>\nIn the src\/app\/pages\/home\/home.page.ts<\/code> file, add the following code:<\/p>\nimport { Component, OnInit } from \"@angular\/core\";\nimport { Router } from \"@angular\/router\";\nimport { AuthenticationService } from \"..\/..\/services\/authentication.service\";\n\n@Component({\n selector: \"app-home\",\n templateUrl: \".\/home.page.html\",\n styleUrls: [\".\/home.page.scss\"],\n})\nexport class HomePage implements OnInit {\n constructor(private authService: AuthenticationService, private router: Router) {}\n\n ngOnInit() {}\n\n logout() {\n this.authService.logout().then(() => {\n this.router.navigateByUrl(\"\/login\");\n });\n }\n}\n<\/code><\/pre>\nNow, if you navigate to the \/home<\/code> route after logging in, you should see the feed page with a logout button.<\/p>\nAdding Firebase Realtime Database<\/h2>\n
To store and retrieve posts from our social media app, we’ll use Firebase Realtime Database.<\/p>\n
First, let’s install the required Firebase modules:<\/p>\n
npm install firebase @angular\/fire\n<\/code><\/pre>\nNow, open the src\/app\/app.module.ts<\/code> file and import the following modules:<\/p>\nimport { AngularFireModule } from '@angular\/fire';\nimport { AngularFireAuthModule } from '@angular\/fire\/auth';\nimport { AngularFireDatabaseModule } from '@angular\/fire\/database';\nimport { environment } from '..\/environments\/environment';\n<\/code><\/pre>\nNext, add AngularFireDatabaseModule<\/code> to the imports section of the @NgModule<\/code> decorator.<\/p>\nThe final app.module.ts<\/code> file should look like this:<\/p>\nimport { NgModule } from '@angular\/core';\nimport { BrowserModule } from '@angular\/platform-browser';\nimport { IonicModule } from '@ionic\/angular';\n\nimport { AppRoutingModule } from '.\/app-routing.module';\nimport { AppComponent } from '.\/app.component';\n\nimport { AngularFireModule } from '@angular\/fire';\nimport { AngularFireAuthModule } from '@angular\/fire\/auth';\nimport { AngularFireDatabaseModule } from '@angular\/fire\/database';\nimport { environment } from '..\/environments\/environment';\n\n@NgModule({\n declarations: [AppComponent],\n entryComponents: [],\n imports: [\n BrowserModule,\n IonicModule.forRoot(),\n AppRoutingModule,\n AngularFireModule.initializeApp(environment.firebase),\n AngularFireAuthModule,\n AngularFireDatabaseModule,\n ],\n providers: [],\n bootstrap: [AppComponent],\n})\nexport class AppModule {}\n<\/code><\/pre>\nBuilding the Post Service<\/h2>\n
Let’s create a service to handle CRUD operations for posts.<\/p>\n
Run the following command to generate a new service:<\/p>\n
ionic generate service services\/post\n<\/code><\/pre>\nOpen the src\/app\/services\/post.service.ts<\/code> file and replace the contents with the following code:<\/p>\nimport { Injectable } from \"@angular\/core\";\nimport { AngularFireDatabase } from \"@angular\/fire\/database\";\nimport { Observable } from \"rxjs\";\n\n@Injectable({\n providedIn: \"root\",\n})\nexport class PostService {\n constructor(private db: AngularFireDatabase) {}\n\n createPost(post: any) {\n return this.db.list(\"posts\").push(post);\n }\n\n getPosts(): Observable<any[]> {\n return this.db.list(\"posts\").valueChanges();\n }\n\n updatePost(postId: string, update: any) {\n return this.db.object(`posts\/${postId}`).update(update);\n }\n\n deletePost(postId: string) {\n return this.db.object(`posts\/${postId}`).remove();\n }\n}\n<\/code><\/pre>\nCreating the Post Form<\/h2>\n
Now, let’s create a form to allow users to create posts.<\/p>\n
Open the src\/app\/pages\/home\/home.page.html<\/code> file and replace its contents with the following code:<\/p>\n<ion-header>\n <ion-toolbar>\n <ion-title>Welcome to the Feed<\/ion-title>\n <\/ion-toolbar>\n<\/ion-header>\n\n<ion-content>\n <ion-button (click)=\"logout()\">Logout<\/ion-button>\n\n <form (submit)=\"createPost()\">\n <ion-item>\n <ion-label position=\"floating\">Post Content<\/ion-label>\n <ion-textarea [(ngModel)]=\"postContent\" required><\/ion-textarea>\n <\/ion-item>\n <ion-button expand=\"full\" type=\"submit\">Create Post<\/ion-button>\n <\/form>\n\n <ion-list>\n <ion-item-sliding *ngFor=\"let post of posts\">\n <ion-item>\n <ion-label>{{ post.content }}<\/ion-label>\n <\/ion-item>\n <ion-item-options>\n <ion-item-option color=\"danger\" (click)=\"deletePost(post.key)\">\n Delete\n <\/ion-item-option>\n <\/ion-item-options>\n <\/ion-item-sliding>\n <\/ion-list>\n<\/ion-content>\n<\/code><\/pre>\nIn the src\/app\/pages\/home\/home.page.ts<\/code> file, add the following code:<\/p>\nimport { Component, OnInit } from \"@angular\/core\";\nimport { Router } from \"@angular\/router\";\nimport { AuthenticationService } from \"..\/..\/services\/authentication.service\";\nimport { PostService } from \"..\/..\/services\/post.service\";\n\n@Component({\n selector: \"app-home\",\n templateUrl: \".\/home.page.html\",\n styleUrls: [\".\/home.page.scss\"],\n})\nexport class HomePage implements OnInit {\n postContent: string;\n posts: any[];\n\n constructor(\n private authService: AuthenticationService,\n private router: Router,\n private postService: PostService\n ) {}\n\n ngOnInit() {\n this.fetchPosts();\n }\n\n fetchPosts() {\n this.postService.getPosts().subscribe((posts) => {\n this.posts = posts;\n });\n }\n\n createPost() {\n const post = {\n content: this.postContent,\n };\n\n this.postService.createPost(post).then(() => {\n this.fetchPosts();\n this.postContent = \"\";\n });\n }\n\n deletePost(postId: string) {\n this.postService.deletePost(postId).then(() => {\n this.fetchPosts();\n });\n }\n\n logout() {\n this.authService.logout().then(() => {\n this.router.navigateByUrl(\"\/login\");\n });\n }\n}\n<\/code><\/pre>\nNow, if you navigate to the home page after logging in, you should see a form to create new posts and a section to display and delete posts.<\/p>\n
Building the Profile Page<\/h2>\n
Finally, let’s create a profile page to display and update user information.<\/p>\n
Run the following command to generate a new page:<\/p>\n
ionic generate page pages\/profile\n<\/code><\/pre>\nOpen the src\/app\/app-routing.module.ts<\/code> file and import the ProfilePage<\/code> and add a new route:<\/p>\n“`typescript
\nimport { NgModule } from “@angular\/core”;
\nimport { RouterModule, Routes } from “@angular\/router”;
\nimport { LoginPage } from “.\/pages\/login\/login.page”;
\nimport { SignupPage } from “.\/pages\/signup\/signup.page”;
\nimport { HomePage } from “.\/pages\/home\/home.page”;
\nimport { ProfilePage } from “.\/pages\/profile\/profile.page”;<\/p>\n
const routes: Routes = [
\n { path: “”, redirectTo: “login”, pathMatch: “full” },
\n { path: “login”, component: LoginPage },
\n { path: “signup”, component: SignupPage },
\n { path: “home”, component: HomePage },
\n { path:<\/p>\n","protected":false},"excerpt":{"rendered":"
In this tutorial, we’ll walk through the steps to build a social media app using Ionic framework and Firebase backend. We’ll cover the essential features like user authentication, posting, liking, and commenting on posts, as well as displaying and updating user profiles. By the end of this tutorial, you’ll have Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[1319,511,221,10,663,1322,34,1321,508,1320,217],"yoast_head":"\nHow to Build a Social Media App with Ionic and Firebase - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n