Angular · Middle · Question 47 of 75

How do you add an auth header to every request?

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};
// provideHttpClient(withInterceptors([authInterceptor]))

Explanation

HttpRequest is immutable, so interceptors call clone. Interceptors run in the order they are listed and can also handle errors, retries, logging and caching.

Further reading

Problem with a question

Angular · Middle · question 47

Test yourself

Take the Angular · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz