Angular Academy · Lesson

Adding Auth Headers

Attach tokens to outgoing requests.

Lesson 2 of 413 steps

Adding Auth Headers is a free Angular Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, and your progress syncs across the web and the CoddyKit app. The Angular Academy course includes 4 lessons in total.

Why intercept for auth

Most APIs require an Authorization header on every request. Rather than adding it manually to each call, an interceptor injects it automatically for all outgoing requests.

Cloning to add a header

Because requests are immutable, clone with setHeaders to attach the token.

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).getToken();
  const authReq = req.clone({
    setHeaders: { Authorization: 'Bearer ' + token }
  });
  return next(authReq);
};

Reading the token from a service

Inject an auth/token service to get the current token. Using a signal or BehaviorSubject inside it keeps the value fresh.

export class AuthService {
  private token = signal<string | null>(null);
  getToken() { return this.token(); }
  setToken(t: string) { this.token.set(t); }
}

Skip when no token

If the user is not logged in, pass the original request through unchanged.

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).getToken();
  if (!token) return next(req);
  return next(req.clone({
    setHeaders: { Authorization: 'Bearer ' + token }
  }));
};

Only attach to your API

Do not leak your token to third-party URLs. Guard by checking the request URL belongs to your backend.

const isApi = req.url.startsWith(environment.apiUrl);
if (!isApi || !token) return next(req);
return next(req.clone({
  setHeaders: { Authorization: 'Bearer ' + token }
}));

setHeaders vs headers.set

setHeaders in clone is the concise way. You can also use req.headers.set(...) and pass it via { headers }. setHeaders merges; it does not replace all headers.

const headers = req.headers.set('Authorization', 'Bearer ' + token);
return next(req.clone({ headers }));

Adding multiple headers

Attach several headers at once in a single clone.

return next(req.clone({
  setHeaders: {
    Authorization: 'Bearer ' + token,
    'X-Client': 'web',
    'Accept-Language': lang
  }
}));

withCredentials for cookies

If auth uses HttpOnly cookies instead of tokens, set withCredentials so the browser sends them cross-origin.

return next(req.clone({ withCredentials: true }));

Refreshing an expired token

For token refresh, the interceptor can catch a 401, request a new token, then retry the original request — a more advanced pattern covered with error handling.

Keeping the interceptor pure

The interceptor should read the token and clone — avoid triggering navigation or heavy logic here. Keep responsibilities focused so the request pipeline stays predictable.

Registering the auth interceptor

Place it early in the chain so the header is present before logging or other interceptors run.

provideHttpClient(
  withInterceptors([authInterceptor, loggingInterceptor])
)

Quick Check

Test your understanding of adding auth headers.

Recap: Adding Auth Headers

An auth interceptor attaches the token to outgoing requests.

  • Clone with setHeaders: { Authorization: ... }.
  • Skip when no token; restrict to your API URL.
  • Use withCredentials for cookie auth.

Next: handling errors globally.

Free to start

Learn HTML with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
38
Lessons
144

Frequently Asked Questions

Is the “Adding Auth Headers” lesson free?

Yes — any 3 lessons of the Angular Academy learning path, including “Adding Auth Headers”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Angular Academy course includes 4 lessons in total.

What will I learn in “Adding Auth Headers”?

Attach tokens to outgoing requests. You practise Angular Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Angular Academy?

No prior experience is required. Angular Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Adding Auth Headers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Angular Academy lesson?

Yes. Every Angular Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Functional Interceptors
  2. Adding Auth Headers
  3. Handling Errors Globally
  4. Retry and Loading Indicators
← Back to Angular Academy