Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Providing a DI token in commonEngine.render() does not provide its value to application #26323

Open
Ozzcer opened this issue Nov 10, 2023 · 107 comments

Comments

@Ozzcer
Copy link

Ozzcer commented Nov 10, 2023

Which @angular/* package(s) are the source of the bug?

Don't known / other

Is this a regression?

Yes

Description

Prior to upgrading to v17 our application passed express' req/res as REQUEST/RESPONSE DI Tokens through the render function of the engine in server.ts. Since upgrading to v17 from v16 these DI Token values are always null.

This can be seen in the minimal reproduction where all three of APP_BASE_HREF / REQUEST / RESPONSE are null in the console output while running 'ng serve'.

If using @angular-devkit/build-angular:browser instead of @angular-devkit/build-angular:application this problem does not occur. I assume there is a different way to provide dependencies from server.ts now but I have not been able to find any updated documentation on it.

Please provide a link to a minimal reproduction of the bug

https://github.com/Ozzcer/angular-ssr-di-issue

Please provide the exception or error you saw

Console outputs null for all DI Tokens provided in server.ts

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 17.0.0
Node: 18.17.1
Package Manager: npm 9.6.7
OS: linux x64

Angular: 17.0.2
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, platform-server
... router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1700.0
@angular-devkit/build-angular   17.0.0
@angular-devkit/core            17.0.0
@angular-devkit/schematics      17.0.0
@angular/cli                    17.0.0
@angular/ssr                    17.0.0
@schematics/angular             17.0.0
rxjs                            7.8.1
typescript                      5.2.2
zone.js                         0.14.2

Anything else?

No response

@Ozzcer Ozzcer changed the title Providing a DI token in commonEngine.render() does not provide this value Providing a DI token in commonEngine.render() does not provide its value to application Nov 10, 2023
@JeanMeche JeanMeche transferred this issue from angular/angular Nov 10, 2023
@JeanMeche
Copy link
Member

Hi, have a look at #26175 which updated the schematics to import create the tokens that aren't exported anymore.
You will need to provide the tokens yourself.

@Ozzcer
Copy link
Author

Ozzcer commented Nov 10, 2023

Hi @JeanMeche , tokens are defined under express.tokens.ts in minimal reproduction (https://github.com/Ozzcer/angular-ssr-di-issue/blob/c08049cc39e2993eff903c29902826a1aa1f7d10/src/express.tokens.ts), this file was created automatically by 'ng update' in our original project and I copied the file over to the minimal reproduction.

Also APP_BASE_HREF is coming through as null and I thought that didn't need to be manually defined.

@alan-agius4 alan-agius4 added needs: more info Reporter must clarify the issue and removed needs: more info Reporter must clarify the issue labels Nov 10, 2023
@alan-agius4
Copy link
Collaborator

This is expected as for ng serve the server.ts is not used.

Whilst we can provide an optional request token, this will be not be same interface of the Express tokens as the dev-server does not use express. Also the mentioned tokens will not available when using prerendering.

The recommended approach to treat the tokens set in server.ts as optional.

@Ozzcer
Copy link
Author

Ozzcer commented Nov 10, 2023

Ah ok, got it working now, I have had to run build and run server.mjs independently. Is there a way to get the dev-ssr-server to work with the application output / is there an equivalent builder available for application output? Or do we still need to use dev-ssr-server with seperate server + browser builder instead of application? The current documentation is quite confusing as it appears like running the application builder through ng serve should allow local ssr rendering

@alan-agius4
Copy link
Collaborator

ng serve does allow SSR, but it does not use the server.ts, Instead it has it's own middlewares and server instance. You should definitly update the docs to make this clear.

@SaeedDev94
Copy link

SaeedDev94 commented Nov 11, 2023

ng serve does allow SSR, but it does not use the server.ts, Instead it has it's own middlewares and server instance. You should definitly update the docs to make this clear.

This is a serious issue IMO, we should be able to inject REQUEST and RESPONSE with ng serve
How we can debug our app then ?
By building and running server.mjs in dist folder ?!
So server.ts is used only for production ??
Or am I missing something ??
I will continue using old ssr-dev-server for now
(I remember that in v16 and below, server.ts was used for both development and production. Why shouldn't it be the same as before? Or if we can use server.ts for both envs + esbuild, how can we do that?)

@Enngage
Copy link

Enngage commented Nov 12, 2023

I've been confused by this as well. I was hoping there is an alternative way for ssr-dev-server in the application builder so that we can both develop the app, have it rebuild on the fly and just use easily.

Since the server.ts is not used for ng serve, it also means that none of the custom API routes that are defined are registered. What is the recommended approach here?

@eneajaho
Copy link
Contributor

eneajaho commented Nov 13, 2023

One other use-case where running server.ts in dev mode (ng serve) would be to be able to change providers.

Ex. In browser I want to use normal assets loading, while in SSR mode I want to be able to read from file-system and inline icons for better perf.
Usecase: https://github.com/push-based/ngx-fast-svg#ssr-usage

I don't see any way to make that work with the current setup.

@SaeedDev94
Copy link

SaeedDev94 commented Nov 14, 2023

Imagine we created a fresh new (SSR) project with latest version of @angular/cli and we want to make sure that angular ssr server returns 404 HTTP Status Code instead of 200 for unregistered routes or we want to redirect a path to another based on some conditions only, so we should set 301 HTTP Status Code and ...
We definitely need server response object to set the right HTTP Status Code (and also request for other use cases)
My question is: How we can do it in development environment ?!

@oriollpz

This comment was marked as spam.

@Ozzcer
Copy link
Author

Ozzcer commented Nov 17, 2023

Not a fix for the issue but if you want to use esbuild found there is a browser-esbuild builder you can drop into an existing angular.json build. If, like myself, you do most development without SSR and then just test in SSR this is an alright method of getting the esbuild benefits in development, but it does warn that its temporary so hopefully before its removed we will be able to use application builder.

@mkurcius
Copy link

mkurcius commented Nov 17, 2023

I have ran into same issue (confusion). I generated fresh app using angular 17, with --ssr option.
Everything looks nice, ng serve was working, until I have a need to create new endpoint in server.ts.
To my surprise my endpoint was not registered, and I was getting ERROR RuntimeError: NG04002: Cannot match any routes. URL Segment: 'api/user'
Initially I though I made a mistake and start trying to fix it, and after sometime of failure after failure, I start realizing maybe server.ts was not part of ng serve?

It was confusing and I waste time trying to fix it.

It was super unintuitive, I had fresh app, generated by CLI, I've run app using ng serve which used default (generated) configuration and to found out server entrypoint was not working 🤯

@SaeedDev94
Copy link

SaeedDev94 commented Nov 18, 2023

One of the request use cases: (user authentication)
Getting the cookie from browser request and add it to api request for protected pages like user profile (with interceptor) + allowing cookie header (angular/angular#15730)
Now without request object we can't do that in dev env (SSR)
And imagine if we already have a guard for the routes !! we can't enter the user profile ...

@FranzStrudel
Copy link

I wasted so much time because it was indeed rendered server side but yet the request provider was empty.

The changelog of the last version (adding node run dist/xxx) put me on the path to this issue.

So confusing behavior.

It has to be at least clearly documented on the getting started page...

@zygarios
Copy link

In reference to my closed but related thread, I believe that the lack of use of server.ts in development mode is a very large regression. There are often things that we need to change there and be able to debug based on the RESPONSE and REQUEST objects. The configuration of this and the work on SSR has unnecessarily become more complicated. I hope that this will be somehow sensibly resolved because in its current form it is impossible for me to work with it on a daily basis and I am forced to use the classic approach in the Angular 16 version.

@oriollpz
Copy link

How do they expect to work authentication with cookies without access to REQUEST RESPONSE from the server.ts?

@osnoser1
Copy link

I agree, in development mode, we should be able to get the request object to do, for example, authentication through the cookie.

This is a breaking change between v16 and v17, and I don't know if it was documented.

santoshyadavdev pushed a commit to uiuniversal/ngu-carousel that referenced this issue Nov 26, 2023
Hello @santoshyadavdev,

This PR fixes #476.

What I did:

- I couldn't use `yarn` at all this time, I switched to `npm` (even
after everything was updated with `npm` and switching back to `yarn`)
- I updated all packages to latest versions (except `jasmine-core`)
- The nx cache is now located in the root folder of the repo, I added
`.nx` in `.gitignore`
- There was some problem with how the tsconfigs were done, I fixed all
of them (it was causing problems with nx migrations)
- I applied the migrations from nx
- I migrated `ngu-carousel-example` to use the new control-flow
  - I did not update the `README.md`
- I removed the cypress component testing config from
`ngu-carousel-example` as it was more or less useless
- I fixed errors found by the linter
- I fixed unit tests
- I removed `updateBuildableProjectDepsInPackageJson` from
`ngu-carousel` as it was deprecated
- removing it keeps the same behavior as if it was enable, that's what
we want
- I added missing `tsconfig.json` (cypress) in the `.eslintrc.json` of
`ngu-carousel`
- I updated the current SSR setup
- I first tried to migrate the new `application` builder, but it was not
working properly with modules. ~~I will investigate later if it comes
from `nx` or the `Angular CLI`~~ (thanks @JeanMeche for his help)
  - Could be related to angular/angular#52998
  - As said in https://riegler.fr/blog/2023-10-13-v17-builders: 
- `An interesting point to note is that if either 'ssr' or 'prerender'
are set to 'true' in the configuration file, the pages served with 'ng
serve' will be generated server side.`
- This was not working, that's one of the reason I kept the same setup
with `ssr-dev-server` & co.
- I already did the migration to `browser-esbuild` when I migrated to
`Angular 16`, so it is already using esbuild.
- Another reason is that `ng serve` using the ssr is not using
`server.ts` (which should not affect this repo, but let's play it safe),
track angular/angular-cli#26323
- I cleaned `polyfills` usage
- I updated the `CI` setup
- Angular supports node starting version `18.13.0`, the CI now runs on
`['18.13.0', '20']`
  - Updated to `actions/checkout@v4` & `actions/setup-node@v4`
  - Updated to use `npm`
- I bumped `ngu-carousel` for `Angular 17`
- I bumped `ngu-carousel` to `9.0.0` and I updated `README.md`

TODO on your side:

- Release a new major version `9.0.0`
- Close branches related to package update

Tell me if everything looks ok for you.

Have a nice day.
@csabe812
Copy link

csabe812 commented Apr 9, 2024

Hi,
I have an Angular 11 (using Angular Universal) project and after struggling with hours I was able to update it to Angular 17 (with SSR). After spending extra 5-6 hours to find the solution I found this open issue. In fact I am facing with the same issue that @mkurcius wrote.
Am I understand correctly that currently there is no way to make fullstack Angular v17 apps using the generated server.ts file?

@zygarios
Copy link

zygarios commented Apr 9, 2024

No, it's not possible for now.
#26323 (comment)

@geexup
Copy link

geexup commented Apr 30, 2024

I need host from headers to properly render og meta tags, and spend so much time to make it work, but providers not providing...

@zygarios
Copy link

This is a known problem and we're working on resolving it. Currently, the plan is to ship it as part of the v18 release this May. If anything unexpected pops up and we're unable to deliver in this timeframe we'll follow up here.

Hey, @mgechev. Is there still a chance for SSR fix in version 18?

@SkyZeroZx
Copy link

I need host from headers to properly render og meta tags, and spend so much time to make it work, but providers not providing...

If you refer usage of meta tags of Document it's possible with Resolver and inject Meta

See this https://medium.com/@shravanvishwakarma5/meta-tags-in-angular-c483c3e6f0d4

Only use in resolvers and work correctly , in my case usage a variant more overhead because i need show imagen a pre prender pages

@AlexVFornazieri
Copy link

I am not the best in Angular. I just wanted to work with server.ts locally in Angular 17. So I came up with the following:

  • Open 2 terminals.
  • On the first terminal run ng build --watch --configuration development. Your code will re-build every time you save the code.
  • On the second terminal run node dist/my-project/server/server.mjs.
  • Reload page after save. Sometimes build is cached, so to fix this, check Disable cache in the Network tab in browser's DEV tools.

This is simple workaround. If someone can show better approach, please reply to this comment. Thanks!

That way works, but losse the hot reload and source maping for all application, anyone have a better workarround for while?

I try improve with nodemon and --enable-source-maps but nothing change, only auto restart the server when files changes, but need refresh the browser.

I'm ussing the server.ts expresse to run API Proxy and Auth routes (Back For Front)

@SaeedDev94
Copy link

For SSR development accessing to server request and response objects is a MUST TO HAVE feature in both development and production envs
This is becoming scary as I didn't see any changes about this issue in development versions of v18
No alternative and clean solution for this until now!
The solutions introduced here are absolutely dirty!!
If this remains without a proper solution (fix or alternative) I'll probably reconsider about my entire frontend stack!!

@Fronikuniu
Copy link

Hello, when can this problem be expected to be solved?

@zygarios
Copy link

zygarios commented May 22, 2024

@Fronikuniu I hope tomorrow with v18 release.

@SkyZeroZx
Copy link

@Fronikuniu I hope tomorrow with v18 release.

Today in my country release Angular 18 but i dont see relative change to issue , I haven't tried it yet in my project

@shady-ahmed-bdr
Copy link

I haven't tried it yet in my project

v18..
Well the only difference is that npm run watch compiles in 5 sec instead of 9 or 10 sec on changes 🤣
it was -1sec/month of improvements , what a fantastic job 🤣🤣🤣🤣🤣
(NO offence!)
still waiting for a fix

@JihedHmida
Copy link

For SSR development accessing to server request and response objects is a MUST TO HAVE feature in both development and production envs This is becoming scary as I didn't see any changes about this issue in development versions of v18 No alternative and clean solution for this until now! The solutions introduced here are absolutely dirty!! If this remains without a proper solution (fix or alternative) I'll probably reconsider about my entire frontend stack!!

sadly i totally agree. i guess no one can start a project with absolutely dirty solutions hoping for fixs..

This is a known problem and we're working on resolving it. Currently, the plan is to ship it as part of the v18 release this May. If anything unexpected pops up and we're unable to deliver in this timeframe we'll follow up here.

and as of version 18 nothing changed ..
nothing is mentioned in the CHANGELOG.md nor in the Angular v18 is now available! blog post.

i don't want be that guy but i guess we waiting for the follow up ..

@SkyZeroZx
Copy link

For SSR development accessing to server request and response objects is a MUST TO HAVE feature in both development and production envs This is becoming scary as I didn't see any changes about this issue in development versions of v18 No alternative and clean solution for this until now! The solutions introduced here are absolutely dirty!! If this remains without a proper solution (fix or alternative) I'll probably reconsider about my entire frontend stack!!

sadly i totally agree. i guess no one can start a project with absolutely dirty solutions hoping for fixs..

This is a known problem and we're working on resolving it. Currently, the plan is to ship it as part of the v18 release this May. If anything unexpected pops up and we're unable to deliver in this timeframe we'll follow up here.

and as of version 18 nothing changed .. nothing is mentioned in the CHANGELOG.md nor in the Angular v18 is now available! blog post.

i don't want be that guy but i guess we waiting for the follow up ..

I hope it is fixed in a minor fix or something soon, which I also hope to update my monorepo project in Nx

@JihedHmida
Copy link

NX upgrades lag behind Angular, usually taking a few days to catch up.
we all aboard the wait train

@rezonant
Copy link
Contributor

I just tried an experimental upgrade to v18 to see if this issue is resolved and it's clear that it has not, though given the lack of any official communication on this issue leading up to release, this outcome is not surprising.

For my team's use case, we didn't have a good way to bring SSR directly into our dev server prior to v17 anyway (given the complexity of our application), so it's not dire that we can't run a valid SSR configuration right now, but clearly other users did have this capability in previous Angular versions with Universal. It's highly unfortunate that the Angular team could not provide even a cursory update about how or whether this issue would be addressed in Angular 18, despite promising to do so (#26323 (comment)). The upgrade marketing was that we would not need Angular Universal at all, because it was all brought into the core framework. As part of that, Angular Universal was never updated to work with v17, so folks who had a solid workflow in the old system either have to abandon SSR in their development workflow or stay behind on previous versions- it looks like that will continue with Angular 18.

The promise of a straightforward, fast dev server native solution for Angular SSR which runs the application's entire codebase is extremely appealing for the community, regardless of whether an SSR dev experience worked prior. Not providing updates on resolution here raises eyebrows.

I'm not mad about v18 not shipping a solution, I'm just incredibly disappointed in the lack of communication. I'm sure I'm not the only one hoping that Angular can provide a suitable explanation for failing to address this in v18. It's highly questionable that the v17 Application Builder was shipped at all without considering what would happen if the core server entrypoint was not executed. I still struggle to understand what the Angular team expected "ssr": true to be useful for with the state it was shipped in.

@Platonn
Copy link
Contributor

Platonn commented May 24, 2024

You might find the following workaround very useful, until Angular fixes this issue - the article by @pawelfras: 🙌

Angular 17: Overcoming SSR Challenges Of The New 'application' Builder 🔎

✅ run SSR dev server
server.ts included
✅ fast application builder
✅ Angular 17+

@quedicesebas
Copy link

I can't do anything useful with SSR without accessing the request in my app 😡.

@zygarios
Copy link

@alan-agius4 Pls, give us some hope for that issue. Any information will be better than nothing

@alan-agius4
Copy link
Collaborator

We are aware of this issue and plan to address it by providing the response/requests DI tokens during ng serve in the version 18 timeframe.

@zygarios
Copy link

Thank you!

@JihedHmida
Copy link

JihedHmida commented May 27, 2024

We are aware of this issue and plan to address it by providing the response/requests DI tokens during ng serve in the version 18 timeframe.

"by providing the response/requests" do you mean just adding the res/req provider or aiming to somehow include the server.ts in the ng serve
there is huge difference between the two..

including the req/res would be better DX but still not full solution.
plus that fix already exist. currently it's bit dirty and not recommended but it works
"https://gist.github.com/andrewatwood/825ae87bfa0d9191cbc38cfbb21cbdab"

you get the request and the res but you can not make custom API routes or custom providers and if you do it wouldn't be registered because the server.ts is still ignored..

@Iemand005
Copy link

I added this back to my angular.json:

"serve-ssr": {
	"builder": "@angular-devkit/build-angular:ssr-dev-server",
	"configurations": {
		"production": {
			"browserTarget": "my-project:build:production",
			"serverTarget": "my-project:server:production"
		},
		"development": {
			"browserTarget": "my-project:build:development",
			"serverTarget": "my-project:server:development"
		}
	},
	"defaultConfiguration": "development"
},

I can run it with:

ng run my-project:serve-ssr

It's the same as Angular 16 and is rather slow but at least works.

@Roman-Simik
Copy link

We are aware of this issue and plan to address it by providing the response/requests DI tokens during ng serve in the version 18 timeframe.

Guys, this is just not enough... our logic is not dependent only on Request/Response objects... We will be able to migrate to the new builder only if the SSR dev server will fully use the server.ts file...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests