Search code examples
angular

I'm getting an error "ReferenceError: localStorage is not defined" in my angular project


In my Angular project, I want to using a localStorage. But I get a error.

Here is my code.

const siteId = this.route.snapshot.queryParamMap.get('SiteId');
if (siteId) {
  this.globalService.setLocalStorage('site_id',siteId);
} else if (!localStorage.getItem("site_id")) {
  this.snackbarService.openSnackbar("Site id is missing", 'error');
}

Here is the error.


ERROR ReferenceError: localStorage is not defined
    at inject (F:\companies\IOT-Billing\source\OnLineSignUp\src\app\modules\auth\login\login.component.ts:16:5)
    at callHookInternal (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:5640:10)
    at callHook (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:5655:7)
    at callHooks (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:5629:9)
    at executeInitAndCheckHooks (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:5598:5)
    at refreshView (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10505:11)
    at detectChangesInView (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10657:5)
    at detectChangesInViewIfAttached (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10640:3)
    at detectChangesInEmbeddedViews (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10616:7)
    at refreshView (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10517:5)

I want to store and get token in localStorage.


Solution

  • When you are using angular application with SSR. The server does not have window, document and localStorage objects available, which I am guessing is the cause of the error.

    When you have SSR, the content will render on the server and the browser, you need to make sure the localStorage is only accessed when you are on the browser.

    Just wrap the localStorage methods in a if condition, that checks if it isn't undefined before performing the action.

    if(typeof localStorage !== 'undefined') {
        localStorage.setItem("bgcolor", "red");
    }