1

Can anyone tell the best way how can we access the browsers local storage in Server Side Rendering in Angular 2? I found out a stackoverflow related to this : localStorage is not defined (Angular Universal) . But i didn't get the concept of providers used in it. Can anyone explain in brief what is the exact meaning of those providers used in main.browser.ts and main.node.ts?

Also i found a module angular-2-localstorage. So which is the best approach to access the local storage in Server side?

Community
  • 1
  • 1
Shailaja shah
  • 846
  • 8
  • 10
  • HTML5 local storage? You can't. It's a client-side feature. – zurfyx Jan 10 '17 at 17:15
  • So how to access local storage at server side? Because in server side rendering our first request goes to server and the rendered HTML gets rendered and returned, so how can server can access local storage there.In my case i have been storing token in local storage.So how can we access that token from server side? – Shailaja shah Jan 10 '17 at 17:19
  • 1
    @zurfyx that's the point of the question.... – Ced Jan 10 '17 at 17:19
  • Possible duplicate of [How to access localStorage in node.js?](http://stackoverflow.com/questions/10358100/how-to-access-localstorage-in-node-js) – zurfyx Jan 10 '17 at 17:22
  • Did you find a solution to this @Shailajashah – Parth Vyas Jan 12 '17 at 12:49
  • As I can see things there is no way for the server to have access to any data that is in the localStorage. In case there is data you need to get from the client when rendering in the server I guess you'll need to use cookies instead. The browser automatically attahces the cookies to any request to the server based on the domain. – Matan Kadosh May 03 '17 at 15:19

1 Answers1

0

The preferred way to do it would be to inject the PLATFORM_ID token into the constructor. The PLATFORM_ID is token that indicates an opaque platform id. Since localStorage is on the DOM, you can utilize a call to isPlatformBrowser() or isPlatformServer() to check if the PLATFORM_ID is on the browser or on the server. If the PLATFORM_ID is on the browser, then the DOM can be accessed, for example:

import { Component, OnInit, Inject, PLATFORM_ID };
import { isPlatformBrowser } from '@angular/common';
....
@Component({

  export class MyComponent implements OnInit {

    constructor(@Inject(PLATFORM_ID) private platformId: Object){}
  
    ngOnInit() {

      if(isPlatformBrowser(this.platformId)){
        //do something
      }

    }
  }
)}

Links

Accessing the DOM in Angular Universal

Local Storage in Angular Universal

Don Vitali
  • 29
  • 5
Kim Merino
  • 286
  • 1
  • 4
  • 16