天天看點

關于自定義的登入機制在SAP Spartacus伺服器端渲染(SSR)實施過程中遇到的問題問題背景

問題背景

某客戶使用了第三方的Authentication service來實作Spartacus使用者的登入機制:

關于自定義的登入機制在SAP Spartacus伺服器端渲染(SSR)實施過程中遇到的問題問題背景

使用token,調用另一個API,擷取user資訊。

We found out that the problem was caused by using this.windowAdapter.getWindow().sessionStorage.* without previously checking if the sessionStorage is actually available. In SSR it was undefined.

If you wrap all the calls in an if (this.windowAdapter.getWindow().sessionStorage) {...} the PLP pages are being SSRed correctly.

As an additional, browser’s storage (sessionStorage, localStorage) API is not available in SSR, therefore code defensively.

自開發的使用者認證:

關于自定義的登入機制在SAP Spartacus伺服器端渲染(SSR)實施過程中遇到的問題問題背景

sessionStorage和localStorage都無法在SSR模式下工作。

關于自定義的登入機制在SAP Spartacus伺服器端渲染(SSR)實施過程中遇到的問題問題背景

This is the reason of SSR not working on the pages where these objects are being used.

If window or localStorage objects are required to be used with SSR then include the library @ng-toolkit/universal .

An example of using window and localStorage objects with SSR can be referred at this article

最佳實踐

最好不要在SSR模式下進行使用者認證(user Authentication)相關的邏輯:

關于自定義的登入機制在SAP Spartacus伺服器端渲染(SSR)實施過程中遇到的問題問題背景

解決方案

I can suggest you to try to inject the @Inject(PLATFORM_ID) protected platform: any (from @angular/core) to your custom-login.component.ts, and then check if the platform is a browser or a server with isPlatformBrowser() or isPlatformServer() ( both coming from @angular/common).

繼續閱讀