Skip to content

Instantly share code, notes, and snippets.

@Mustafa-Omran
Last active September 20, 2024 08:58
Show Gist options
  • Select an option

  • Save Mustafa-Omran/0b411c89deef26a155273b9860735396 to your computer and use it in GitHub Desktop.

Select an option

Save Mustafa-Omran/0b411c89deef26a155273b9860735396 to your computer and use it in GitHub Desktop.
Angular +17 Interceptor (HttpInterceptorFn)
import { User } from '@amaleyat/shared/models/user';
import { isPlatformBrowser } from '@angular/common';
import { HttpInterceptorFn } from '@angular/common/http';
import { inject, PLATFORM_ID } from '@angular/core';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const platformId: Object = inject(PLATFORM_ID);
if (isPlatformBrowser(platformId)) {
const user: User = JSON.parse(localStorage.getItem('user') || '{}');
if (user?.access_token) {
const authReq = req.clone({
setHeaders: {
'Accept': '*',
'Content-Type': 'application/json',
'Authorization': `Bearer ${user?.access_token}`,
},
});
return next(authReq);
}
}
return next(req);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment