Angular HTTP Interceptors for JWT and Error Handling

Day 43 of #100DaysOfCode 𝐀𝐧𝐠𝐮𝐥𝐚𝐫 𝐇𝐓𝐓𝐏 𝐈𝐧𝐭𝐞𝐫𝐜𝐞𝐩𝐭𝐨𝐫𝐬: 𝐓𝐡𝐞 𝐆𝐥𝐨𝐛𝐚𝐥 𝐏𝐨𝐰𝐞𝐫𝐡𝐨𝐮𝐬𝐞 𝐟𝐨𝐫 𝐉𝐖𝐓 & 𝐄𝐫𝐫𝐨𝐫𝐬 If you find yourself manually adding headers to every 𝐻𝑡𝑡𝑝𝐶𝑙𝑖𝑒𝑛𝑡 call or writing the same 𝑡𝑟𝑦/𝑐𝑎𝑡𝑐h block for every API request, you need HTTP Interceptors. Think of an Interceptor as a "Security Gate" or a "Middleman" that sits between your Angular app and your backend. Every request going out and every response coming in passes through it. 𝟏. 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠 𝐉𝐖𝐓 𝐓𝐨𝐤𝐞𝐧𝐬 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲 Instead of injecting a token in every service, an Interceptor can intercept the outgoing request, clone it, and inject the 𝐴𝑢𝑡𝑕𝑜𝑟𝑖𝑧𝑎𝑡𝑖𝑜𝑛 header globally. 𝟐. 𝐆𝐥𝐨𝐛𝐚𝐥 𝐄𝐫𝐫𝐨𝐫 𝐋𝐨𝐠𝐠𝐢𝐧𝐠 & 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠 Interceptors are also the perfect place to catch HTTP errors (like 401 Unauthorized or 500 Server Error) before they reach your components. 𝐖𝐡𝐲 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐚 "𝐂𝐥𝐞𝐚𝐧 𝐂𝐨𝐝𝐞" 𝐦𝐮𝐬𝐭-𝐡𝐚𝐯𝐞? • 𝐃𝐑𝐘 (𝐃𝐨𝐧'𝐭 𝐑𝐞𝐩𝐞𝐚𝐭 𝐘𝐨𝐮𝐫𝐬𝐞𝐥𝐟): You write your auth logic once. Every new service you create automatically becomes "secure" without extra code. • 𝐂𝐞𝐧𝐭𝐫𝐚𝐥𝐢𝐳𝐞𝐝 𝐋𝐨𝐠𝐢𝐜: If your backend changes its token format or error structure, you only change code in one file. • 𝐒𝐞𝐩𝐚𝐫𝐚𝐭𝐢𝐨𝐧 𝐨𝐟 𝐂𝐨𝐧𝐜𝐞𝐫𝐧𝐬: Your data services stay focused on what data to fetch, while the Interceptor handles the how (security, logging, retries). #Angular #TypeScript #WebDevelopment #CleanCode #RxJS #SoftwareArchitecture

  • text

Tu pourrais refresh au lieu de logout ou bien de logout que si tu n’arrive pas à refresh

To view or add a comment, sign in

Explore content categories