I have an Angular 6+ app which is configured to utilize server side rendering using Angular Universal.
I also used TransferState to avoid duplicate API calls on the server and client app.
Authentication in my angular app is based on token.
The problem is in the first time the user opens my web app, which results to rendering index.html for a user which is not authenticated whereas the user actually is logged in but there is no opportunity to transfer the token to the server. So, when the client app swapped with server app, it is required to call APIs again because of the existance of token in the browser's localStorage/sessionStorage.
I used node.js and express.js to implement server side rendering.
I think the solution is to use session and cookies. This requires a lot of work for me since I'm not familiar with node.js to handle sessions/cookies. Is there any fast and easy solution?
For others facing the same problem, here is the solution.
client-app should save the state data required for server side rendering (e.g. authentication info) in the browser cookies. Browser will automatically sends cookies in header of the first request to fetch
index.html
. Then in theserver.js
we should extract cookie from request header and pass it to server-app usingextraProviders
ofrenderModuleFactory
.First thing we need is a service to deal with browser cookies. I declared one inspired from this post (github repo link)
Next we save data (which we want to pass to the server-app) in cookie of browser
Finally in
server.ts
extract token and pass it to server-app:and use the provided cookie in a service like this:
In the providers of
app.server.module.ts
use theServerStorage
in theStubBrowser
Here is the stub browser, window and document I used: