ngxs / store

🚀 NGXS - State Management for Angular
http://ngxs.io
MIT License
3.54k stars 402 forks source link

Storage Plugin SSR localStorage is not defined #1118

Closed Dav1dde closed 5 years ago

Dav1dde commented 5 years ago

I'm submitting a...

[ ] Regression (a behavior that used to work and stopped working in a new release)
[X] Bug report  
[ ] Performance issue
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => https://github.com/ngxs/store/blob/master/CONTRIBUTING.md
[ ] Other... Please describe:

Current behavior

SSR fails with

ReferenceError: localStorage is not defined
    at engineFactory (app/dist/server.js:152303:9)
    at _callFactory (app/dist/server.js:24259:20)
    at _createProviderInstance (app/dist/server.js:24215:26)
    at initNgModule (app/dist/server.js:24145:32)
    at new NgModuleRef_ (app/dist/server.js:24872:9)
    at Object.createNgModuleRef (app/dist/server.js:24861:12)
    at NgModuleFactory_.create (app/dist/server.js:27396:25)
    at app/dist/server.js:20742:43
    at ZoneDelegate.invoke (app/dist/server.js:546:26)
    at Object.onInvoke (app/dist/server.js:20276:33)

I have seen #465 but this is either a regression or was never really fixed. I am using the STORAGE_ENGINE workaround but this does not solve the issue, localStorage is still undefined and throws an exception.

Relevant code from server.js:

function engineFactory(options) {
          if (options.storage === 0 /* LocalStorage */) {
              // todo: remove any here
              return (/** @type {?} */ (localStorage));
          }
          else if (options.storage === 1 /* SessionStorage */) {
              return (/** @type {?} */ (sessionStorage));
          }
          return null;
}

Identical to: https://github.com/ngxs/store/blob/master/packages/storage-plugin/src/storage.module.ts#L23

Expected behavior

SSR does not fail and storage is either ignored or stubbed.

Minimal reproduction of the problem with instructions

Angular Universal example, add NGXS and NGXS Storage modules.

Environment

Libs:
- @angular/core version: 7.2.0
- @ngxs/store version: 3.4.3 (also happens in current master)


For Tooling issues:
- Node version: 11.15.0  
- Platform:  Linux
splincode commented 5 years ago

You can send pull request

Dav1dde commented 5 years ago

I will look into it when I get home.

arturovt commented 5 years ago

@Dav1dde I will investigate today

Dav1dde commented 5 years ago

I went ahead and opened a PR, input highly appreciated.

arturovt commented 5 years ago

@Dav1dde

Could you install the latest version yarn add @ngxs/storage-plugin@dev and check if it's working correctly? So we're able to add it to the 3.5.0 milestone

Dav1dde commented 5 years ago

Works perfectly!

{
    "@ngxs/storage-plugin": "^3.4.3-dev.master-3528deb",
    "@ngxs/store": "^3.4.3-dev.master-3528deb",
}
splincode commented 5 years ago

Released in 3.5.0