Ionic 8 and Angular 20 Tutorial: HTTP Interceptor Example

by Didin J. on Jul 28, 2025 Ionic 8 and Angular 20 Tutorial: HTTP Interceptor Example

Learn how to use HTTP Interceptors in Ionic 8 and Angular 20 to inject JWT tokens into requests, log activity, and handle errors globally in your app.

Handling HTTP requests securely and efficiently is a core requirement of any modern web or mobile application. In Angular-based Ionic apps, HTTP interceptors provide a powerful and elegant way to automatically attach headers (like JWT tokens), handle errors globally, log traffic, or even manipulate requests and responses.

In this updated tutorial, we’ll show you how to create a simple yet powerful HTTP interceptor in an Ionic 8 and Angular 20 app. You'll learn how to:

  • Create a new Ionic Angular project

  • Implement an interceptor that attaches an Authorization header

  • Inject services into the interceptor

  • Use Angular’s HttpClient for making secure API requests

  • Register the interceptor globally within your app

By the end of this tutorial, you’ll have a working example that demonstrates how to intercept and modify HTTP requests—laying the groundwork for robust authentication and secure data communication in your Ionic apps.


Step 1: Create an Ionic 8 Angular App

Prerequisites

Make sure you have the latest tools installed:

npm install -g @ionic/cli

Check versions:

ionic --version      # Should be 8.x.x
node --version       # Recommended: v20+

📦 Create a New Ionic App with Angular

ionic start http-interceptor-example blank --type=angular
cd http-interceptor-example

Choose Angular when prompted. Run the Ionic app for the first time.

ionic serve

Now, open the browser and the inspect mode.

Ionic 4 and Angular 7 Tutorial: HTTP Interceptor Example - Blank Ionic 4 Angular 7 App


Step 2: Generate the HTTP Interceptor

Use Angular CLI inside the project to generate the interceptor file.

ng generate interceptor interceptors/auth

This creates src/app/interceptors/auth.interceptor.ts.

Edit the file like so:

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const cloned = req.clone({
      setHeaders: {
        Authorization: `Bearer FAKE-JWT-TOKEN`
      }
    });

    console.log('Intercepted request:', cloned);

    return next.handle(cloned);
  }
}


Step 3: Register the Interceptor

Update src/main.ts to include the interceptor:

import { bootstrapApplication } from '@angular/platform-browser';
import { RouteReuseStrategy, provideRouter, withPreloading, PreloadAllModules } from '@angular/router';
import { IonicRouteStrategy, provideIonicAngular } from '@ionic/angular/standalone';

import { routes } from './app/app.routes';
import { AppComponent } from './app/app.component';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './app/interceptors/auth.interceptor';

bootstrapApplication(AppComponent, {
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    provideIonicAngular(),
    provideRouter(routes, withPreloading(PreloadAllModules)),
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
  ],
});


Step 4: Create Auth Service

Create a simple service that will make an HTTP request using Angular’s HttpClient.

ng generate service services/auth

Update the file src/app/services/auth.service.ts with:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private apiUrl = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) { }

  getPosts(): Observable<any> {
    return this.http.get(this.apiUrl);
  }
}

ℹ️ You can replace the dummy jsonplaceholder URL with your own backend API.


Step 5: Use the Service in AppComponent

Open src/app/app.component.ts and call the getPosts() method to test the interceptor:

import { Component, OnInit } from '@angular/core';
import { IonApp, IonRouterOutlet } from '@ionic/angular/standalone';
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  imports: [IonApp, IonRouterOutlet],
})
export class AppComponent implements OnInit {
  data: any;

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authService.getPosts().subscribe((res) => {
      this.data = res;
    });
  }
}

🧪 You should now see the API response printed on screen, and the browser console will show the intercepted request with a fake token added.


Step 6: Run the App

Run your Ionic 8 Angular app with:

ionic serve

Open DevTools console — you should see your Authorization header added by the interceptor.

Ionic 8 and Angular 20 Tutorial: HTTP Interceptor Example - Login page
Ionic 8 and Angular 20 Tutorial: HTTP Interceptor Example - Register Page
Ionic 8 and Angular 20 Tutorial: HTTP Interceptor Example - Register Success
Ionic 8 and Angular 20 Tutorial: HTTP Interceptor Example - Login with username and password


Step 7: Optional Improvements

Here are a few ideas to improve the HTTP interceptor setup:

✅ 1. Dynamic Token Injection

Replace the hardcoded token with a real one, typically from a service:

const token = this.authService.getToken(); // from a real auth service
const cloned = req.clone({
  setHeaders: {
    Authorization: `Bearer ${token}`
  }
});

✅ 2. Handle Errors in Interceptor

You can handle HTTP errors globally:

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

return next.handle(cloned).pipe(
  catchError((error) => {
    console.error('HTTP Error:', error);
    return throwError(() => error);
  })
);

✅ 3. Add Multiple Interceptors

You can create multiple interceptors (e.g., for error handling, loading spinners, logging) by adding them to the providers array using multi: true.


Conclusion

In this updated tutorial, you learned how to:

  • Create a modern Ionic 8 + Angular 20 app

  • Implement a reusable HTTP Interceptor

  • Inject an Authorization token into outgoing requests

  • Consume a simple API using Angular’s HttpClient

  • Structure your services and modules using Angular best practices

This pattern is essential for handling JWT tokens, global error handling, and logging in real-world Ionic apps.

You can find the full working source code on our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 6 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advanced Ionic Template.

That's just the basics. If you need more deep learning about Ionic, Angular, and TypeScript, you can take the following cheap course:

Thanks!