title: How to fix refresh access token from the first http request which gives GET 401 error
body: <p>The problem is that, when the <code>access token</code> is expired and I do any click, then access token does not refresh. But when I do the second click, it refreshes. For the first click, I get '<code>GET 401 error</code>'. The actual problem for me is to get access token before any HTTP request in the <code>interceptor</code>.</p>
  
  <p>I tried <code>switchMap</code> for my code to wait for the access token, but it didn't work.
  Do you have any ideas how could I fix this?</p>
  
  <pre><code>export class DevelopmentInterceptor implements HttpInterceptor {
      constructor(
          private authService: AuthService,
          private router: Router,
          private toastr: ToastrService,
          private translate: TranslateService
      ) { }
  
  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
      const headers = new HttpHeaders({
          'Content-Type': 'application/json; charset=utf-8',
          'Authorization': `Bearer ${this.authService.getAccessToken()}`
      });
      let apiReq = null;
      if (req.url.indexOf('i18n') &gt;= 0) {
          apiReq = req;
      } else if (req.url.indexOf('token') &gt;= 0) {
          apiReq = req.clone({ url: environment.authServerUrl + `${req.url}` });
      } else if (req.url.indexOf('sign-up') &gt;= 0) {
          apiReq = req.clone({ url: environment.signupUrl });
      } else if (req.url.indexOf('api/users') &gt;= 0 || req.url.indexOf('api/roles') &gt;= 0 || req.url.indexOf('api/permissions') &gt;= 0) {
          apiReq = req.clone({ headers: headers, url: environment.authServerUrl + `${req.url}` });
      } else {
          apiReq = req.clone({ headers: headers, url: environment.backenUrl + `${req.url}` });
      }
  
      if (req.url.endsWith('token')) {
          return next.handle(apiReq).catch((err: any) =&gt; { //&lt;--if error use a catch
              if (err instanceof HttpErrorResponse) {
                  return this.handleError(err);
              }
          });
      } else {
          return this.authService.checkExpiry().switchMap( (result) =&gt; {
              if (result) {
                  return next.handle(apiReq)
                      .catch((err: any) =&gt; { // &lt;--if error use a catch
                          if (err instanceof HttpErrorResponse) {
                              return this.handleError(err);
                          }
                      });
              }
          } )
      }
  }
  
  private handleError(err: Response | any) {
          ...
      }
  }
  
  public checkExpiry() : Observable&lt;any&gt; {
      if (!this.cookieService.get('user_id')) {
          this.removeTokens();  // not logged in
          return Observable.of(true);
      } else if (!this.cookieService.check('access_token')) {
          if (this.cookieService.check('refresh_token')) {
              if (this.secondsTillExpiry('refresh_token') &gt; 0) {
                  return this.refreshAccessToken().switchMap((data:any) =&gt; {
                      if (data) {
                          this.saveTokenInCookies(data);
                          this.updateExpiration(data);
                          return Observable.of(true);
                      }
                  })
              } else {
                  this.router.navigate(['/login']);
                  this.removeTokens();
                  return Observable.of(true);
              }
          }
      } else if (this.cookieService.check('access_token') ) {
          return Observable.of(true);
      }
  }
  
  
  
  public secondsTillExpiry(tokenMode: string): any {
      if (tokenMode == 'access_token') {
          return  ((new Date(1970, 0, 
                   1).setSeconds(jwt_decode(this.getAccessToken()).exp)) - 
                   (Math.round(Date.now()) / 1000));
      } else  if (tokenMode == 'refresh_token') {
          return  ((new Date(1970, 0, 
                   1).setSeconds(jwt_decode(this.getRefreshToken()).exp)) - 
                   (Math.round(Date.now()) / 1000));
        }
      }
  
  private refreshAccessToken(): Observable&lt;Object&gt; {
      const params = 'refresh_token=' + this.getRefreshToken() + 
  '&amp;grant_type=refresh_token';
      return this.http.post(this.authUrl, params, this.getOptions());
  
  }
  </code></pre>