🎉 New in Angular v12 — Passing Context to HTTP Interceptors

Netanel Basal
Netanel Basal
Published in
2 min readMar 19, 2021

It’s finally here. In Angular v12 (next), there is a new functionality we’re all been waiting for — passing metadata to HTTP interceptors. No more dirty hacks, such as using an HTTP header to pass custom data that our interceptor needs.

One common use case is to notify the interceptor that a request is cacheable. Let’s see how we use it.

First, update to the latest version of Angular. Next, create a new interceptor:

ng g interceptor cache

Next, we need to create a unique token using HttpContextToken and provide a default value for it. A token is used to manipulate and access values stored in HttpContext.

HttpContext stores arbitrary user-defined values and ensures type safety without actually knowing the types.

The context is mutable and is shared between cloned requests unless explicitly specified.

Finally, we can provide it in our HTTP request:

🚀 In Case You Missed It

Here are a few of my open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • error-tailer — Seamless form errors for Angular applications
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests
  • Error Tailor — Seamless form errors for Angular applications

And many more!

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (4)