Search code examples
angulartypescript

How to use localStorage in Angular 18 HttpInterceptorFn?


I'm new in Angular and I'm trying to get access and refresh tokens from localStorage in http interceptor, but I'm getting this error: Page /admin did not render in 30 seconds.

auth.interceptor.ts:

import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const accessToken = localStorage.getItem('access');
  const refreshToken = localStorage.getItem('refresh');

  return next(req);
};

profile.component.ts:

import { Component, OnInit } from '@angular/core';
import { UserService } from '../../services/user.service';
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { User } from '../../models/user';

@Component({
  selector: 'app-profile',
  standalone: true,
  imports: [],
  templateUrl: './profile.component.html',
  styleUrl: './profile.component.scss'
})
export class ProfileComponent implements OnInit {
  user: User | null = null;
  isFailed = false;

  constructor(
    private userService: UserService,
    private route: ActivatedRoute,
    private titleService: Title) { }

  ngOnInit(): void {
    this.route.paramMap.subscribe((paramMap) => {
      const username = String(paramMap.get('username'));

      this.userService.getUser(username).subscribe({
        next: (user) => {
          this.isFailed = false;
          this.user = user;
          this.titleService.setTitle(`${this.user.display_name || this.user.username} profile`);
        },
        error: () => {
          this.isFailed = true;
        }
      });
    });
  }
}

If I remove localStorage.getItem() functions then error disappears.


Solution

  • You probably don't need prerendering.

    disable it by removing prerender: true from your angular.json.