How to use localstorage on Angular when enabling ssr
Asked Answered
S

2

6

I'm working on a Angular project that used localstorage. The project is a web application of a travel agency. In this web app, the first time a visitor arrived we display prices with a default currency. What i have done is that, when the visitor change the currency, i store the choosen currency in localstorage so that the next time he came on our web app, i just have yo take there his favorite currency ans display prices related to it. I have plan to do it with other data like languages and other ones.

Before enabling ssr on project, everything was working fine but now i'm facing the issue "localstorage is undefined".

Before anything, what i really want to confirm is that: is it possible to store data on server side so that a user can recover them even if he close the web app on browser and open it again ?

Will the server store individual data for all users, so that they recover them every time ? I mean before ssr enabling, i know that each one browser would have store individual choosen currency.

If refreshing the page and using localstorage on server side ,will all data store in storage will be removed ?

Is it Another way to properly handle this ?

Please guys i'm a french native speaker so, i apologize for my english level.

I am a self-taught web developer Please be lenient in your answers

Thanks for your help.

Strained answered 27/7, 2022 at 5:29 Comment(0)
K
0

localstorage in ssr is meaningless. you can use this:

private isBrowser!: boolean

constructor(@Inject(PLATFORM_ID) private platformId) {
  this.isBrowser = isPlatformBrowser(platformId)
}

ngOnInit(): void {
  if (this.isBrowser) {
    localStorage.setItem('key', value)
  }
}

if you want to work with states computed in server side you can use redis or using a database(which is a bad idea)

UPDATE:

you have to set or get localstorage items with this:

if (this.isBrowser){
  localStorage.setItem('key', value);
  localStorage.getItem('key');
}

if you use this in first of ngOnInit your problem will be resolved:

if (this.isBrowser){
  localStorage.getItem('key');
}

NOTE:

you can also use ngrx that is a complicated costly solution if you want just for this case.

Kinswoman answered 27/7, 2022 at 5:41 Comment(2)
The users don't have to create an account to visit the web app for the moment. Ok, i will look for redisStrained
you can also use ngrx that is a complicated costly solution if you wnat just for this case.Kinswoman
S
0

localStorage can be used in the client's browser. Just make sure to wrap the code in afterRender or afterNextRender lifecycle hooks, see the SSR docs:

class MyComponent {
  updateStorage() {
    afterNextRender(() => {
      localStorage.setItem('my-key', 'My value');
    });
  }
}

On server side this doesn't work, as in NodeJS there is no local storage.

Sunnysunproof answered 16/5 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.