Intercepting HTTP requests in Angular, but not making any changes to the

Working on Angular 13, I am trying to attach a JWT token to the headers in order to access a restricted route on the backend. However, after inspecting the backend, it seems that the JwtInterceptor is not modifying the HTTP request headers. I have included the HttpClientModule only once in my project, specifically in the root AppModule. To debug the issue, I added a pipe function with error handling to the next object within the interceptor based on a suggestion from a similar problem on SO, but it did not provide any solution.

I even went as far as adding console.log statements within the file, however, there was no output, which leads me to believe that the interceptor might not be firing at all.

I have previous experience working with interceptors and never encountered this issue before, so I am puzzled. The main difference here is that I am dealing with an Angular PWA. My understanding was that a service worker should not interfere with the behavior of an interceptor. Could a POST request trigger a "cache busting" event?

Could the error lie in the implementation of the PWA? Despite following the documentation, I cannot rule out the possibility.

The attachments include the App Module, Jwtinterceptor, and the "Barrel" of HttpInterceptors. I intend to add more interceptors to the project and hence followed the suggestion in the docs to create a Barrel.

TL;DR
The HttpInterceptor (JwtInterceptor) does not seem to be functioning at all. This approach has worked for me in past projects, the only variation being the use of a PWA in this particular project. Unsure if there is a conflict or peculiar aspect related to PWA implementation. HttpClientModule is present only once in the project.

app.module.ts

//Angular level imports
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

// Rest of the imports...

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    HeaderComponent,
    // Other components...
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    AngularMaterialModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: environment.production,
      registrationStrategy: 'registerWhenStable:30000',
    }),
    HttpClientModule,
    RouterModule,
  ],
  providers: [httpInterceptorProviders],
  bootstrap: [AppComponent],
})
export class AppModule {}

jwt.interceptor.ts

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { environment } from '@environments/environment';
import { AccountService } from '@app/_services/account.service';


@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(private accountService: AccountService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const user = this.accountService.currentUserValue;
    const isLoggedIn = user && user.jwt;
    const isApiUrl = request.url.startsWith(environment.apiUrl);
    if (isLoggedIn && isApiUrl) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${user.jwt}`,
        },
      });
    }

    return next.handle(request);
  }
}

index.ts - "Barrel" file

/* "Barrel" of Http interceptors */
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './jwt.interceptor';

/* Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
];

Post request Headers https://i.sstatic.net/bAHVm.png

Answer №1

Swap out setHeaders for headers.

request = req.clone({
    headers: req.headers.append('Authorization', `Bearer ${user.jwt}`)
});

It appears that the problem arises from your condition not being satisfied.

Answer №2

Gratitude to those who provided assistance.

The challenge arose when I attempted to convert my app into a PWA. It turned out that the service worker was interfering with my token interceptor. After removing the PWA feature, my app started functioning properly again. So, caution is advised if your interceptors cease to work after implementing a service worker; the issue may lie elsewhere.

I recommend that anyone looking to transform their working app into a PWA should not only read the docs but also follow a more thorough tutorial. In my experience, the Angular documentation on advanced topics lacks context and can be somewhat disconnected from real-world application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fresh React framework

I haven't worked on a React app in a while, but when I decided to start a new one and import my old function, I encountered the following error: C:/Users/Hello/Documents/Dev/contacts/client/src/App.tsx TypeScript error in C:/Users/Hello/Documents/Dev ...

Develop a cutting-edge Drag and Drop Functionality using the innovative Material CDK

Here is a unique link you can check out: https://stackblitz.com/angular/nabbkobrxrn?file=src/app/cdk-drag-drop-enter-predicate-example.ts. In this example, I have specific goals: I want to be able to select only one number from the "Available numbers" l ...

Encountered an error while attempting to update an object: Unable to read property 'push' of undefined

Encountering an issue while attempting to update an object with additional information, receiving an error message stating 'property \'push\' of undefined'. /*Below is the object model in question:*/ export class Students { ...

`Node.JS app having issue displaying AngularJS code on Localhost`

I have successfully created a Node.JS application, where I implemented my own HTTP server within the main JS file. The HTML and CSS render correctly on localhost, and even JQuery works when imported via CDN. However, I am facing an issue with displaying ba ...

What is the best way to exclude an interface using a union type recursively in TypeScript?

I wish to recursively exclude types that are part of union types, and eliminate certain union types Here is an example. Normal and Admin should be considered as union types interface Admin { admin: never; } interface Normal { normal: never; } ...

ngOnChanges fails to trigger

I have set up a StackBlitz example (without server side code) which demonstrates an issue with reassigning a variable asynchronously from the backend. I need to update these values so that all objects in the array are of the same type for use in a select ...

Having trouble locating the .ts module when executing a Node script with experimental modules enabled

I am currently developing a node express project and I need to run a node script from the terminal. Within my project, there are some .ts files that I want to include in the script (MyScript.js). Below is the content of MyScript.js: import get from &apos ...

Is it possible to set up TypeScript npm packages to be installed in their original TypeScript format rather than JavaScript for the purpose of examining the source code?

Despite my lack of expertise in the inner workings of how a TypeScript library compiles itself to JavaScript before being placed in the node_modules directory, I have a question: Coming from a PHP background, I am accustomed to being able to explore any l ...

I'm trying to figure out how to access the array field of an object in TypeScript. It seems like the type 'unknown' is required to have a '[Symbol.iterator]()' method that returns an iterator

I'm currently tackling an issue with my helper function that updates a form field based on the fieldname. For example, if it's the name field, then form.name will be updated. If it's user[0].name, then the name at index 0 of form.users will ...

A guide to sorting through in-app notifications in REACT-NATIVE based on their read status

Incorporating two headings, "Unread" and "Read", into the notification system is my goal. When opened, the Unread Notifications should be displayed beneath the Read notifications. This data is being retrieved from an API. Each notification contains a key ...

The requested resource could not be located at @angular/platform-browser.js

I am attempting to set up ASP.NET MVC 5 (not Core) + Angular 2.0.0 + JSPM + SystemJS + TS Loader. Upon running the application, I encounter the following error: Failed to load resource: the server responded with a status of 404 (Not Found) http://localho ...

The lazy loading feature is affected by Angular's ng build process

My app has lazy loading configured and works fine with ng serve. However, when I use ng build, it stops working without any error messages. I have checked the Angular official documentation and can't seem to find any missing steps in my process. I in ...

Obtaining user roles from server without using JWT tokens

My main objective is to provide user roles from the backend. For instance, if a user wishes to access resources in my backend, they can log in using Google credentials. The Angular app retrieves the access token from the Google authorization server and s ...

Learn the method for triggering events with a strongly-typed payload in Vue 3 Composition API and TypeScript

I'm currently exploring Vue 3 Composition API along with TypeScript, particularly focusing on emitting events with a strictly typed payload. There's an example provided below, but I'm unsure if it's the most effective way to achieve t ...

Is there a simpler and more refined approach for handling Observables within RxJS pipelines?

Picture this: I have an observable that gives me chocolate cookies, but I only want to eat the ones without white chocolate. Since I am blind, I need to send them to a service to determine if they are white or not. However, I don't receive the answer ...

What steps can be taken to resolve the TS5023 error that arises when including "allowImportingTsExtensions" in the tsconfig.json file?

While working on my React project, I've encountered a specific error that reads: Could not parse tsconfig.json. Please ensure it contains valid JSON syntax. Details: error TS5023: Unknown compiler option 'allowImportingTsExtensions'. I tr ...

TS: Utilizing a generic parameter in an overloaded function call

This piece of code encapsulates the essence of what I'm trying to achieve more effectively than words: function A(a: string): string; function A(a: number): number; function A(a: any) { return a; } function B<T extends number | string>(arg: T): ...

Strategies for avoiding unused style tags in React components

Expanding beyond React, I'm unsure if React itself is the culprit of this issue. In a React environment with TypeScript, I utilize CSS imports in component files to have specific stylesheets for each component. I assumed these styles would only be ad ...

Having difficulty pushing Angular project to Github

Trying to push my angular project to Github has been a bit challenging. The project's structure consists of: backend (Node API) frontend (Angular) .gitignore To push the angular project, I navigated to the root folder and ran the following commands: ...

Issue with Angular Provider Missing in Ahead-Of-Time Compilation

My goal is to simplify the declaration of a provider by using a static function in this way: const provider = MyModule.configureProvider(); @NgModule({ bootstrap: [AppComponent], declarations: [AppComponent], imports: [ ... ], providers: [ ...