I am working on a website using angular server side rendering (SSR). The whole thing renders perfectly if no HTTP requests are performed in the app.
BUT, as soon there is, the app renders but does not take the returned data to render the pages, and errors start to appear in the console.
- Setup
My setup is a regular Angular 15.1 app with @nguniversal/express-engine
to render static pages.
I also run Strapi (a NodeJS headless CMS on a separate port) as my API over post 8000.
- I added
http-proxy-middleware
to theserver.ts
file in order to proxy the/api
calls to the Strapi server.
server.use('/api', (req, res) => {
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
logLevel: 'debug',
});
});
- I've decided to keep my test simple by keeping only one page of my app to test the HTTP request.
My Home page route contains a resolve to get the data from the API, which it does successfully when running the project with npm run dev:srr
except that I see an error in my console pertaining to my angular code:
ERROR TypeError: Cannot read properties of undefined (reading 'attributes')
at getHomePageContentSuccess (./src/app/home/home.component.ts:224:34)
at ngOnInit (./src/app/home/home.component.ts:215:10)
at callHook (./node_modules/@angular/core/fesm2020/core.mjs:2488:22)
at callHooks (./node_modules/@angular/core/fesm2020/core.mjs:2457:17)
at executeInitAndCheckHooks (./node_modules/@angular/core/fesm2020/core.mjs:2408:9)
at refreshView (./node_modules/@angular/core/fesm2020/core.mjs:10434:21)
at refreshEmbeddedViews (./node_modules/@angular/core/fesm2020/core.mjs:11434:17)
at refreshView (./node_modules/@angular/core/fesm2020/core.mjs:10443:9)
at refreshComponent (./node_modules/@angular/core/fesm2020/core.mjs:11480:13)
at refreshChildComponents (./node_modules/@angular/core/fesm2020/core.mjs:10210:9)
Here, attributes
is me trying to get to a property that is returned by the API. It works in the browser, but not on the server.
private getHomePageContentSuccess(data: IDataPayload<IHomePayload>): void {
this.homeContent = data.data.attributes; // this works in the browser, but throws in server console
}
- When I run
npm run prerender
, I get the same error.
It looks like when the angular is bootstrapped on the server side, it performs the call (which isn't hitting Strapi), ends up in the success handler but without any data, thus throwing the attributes
error.
I'm at a loss, I have no idea how to move past this issue.
I tried the angular proxy file, passing the proxy config in command line, I tried adding a proxy in the server.ts
file... it does not seem to be proxy related at all.