Skip to content

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

Closed

Description

@Ozzcer

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

Activity

  1. 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[/+] on Nov 10, 2023
  2. transferred this issue fromangular/angularon Nov 10, 2023
  3. JeanMeche commented on Nov 10, 2023

    @JeanMeche
    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.

  4. Ozzcer commented on Nov 10, 2023

    @Ozzcer
    Author

    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.

  5. added
    needs: more info
    and removed
    needs: more info
    on Nov 10, 2023
  6. alan-agius4 commented on Nov 10, 2023

    @alan-agius4
    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.

  7. Ozzcer commented on Nov 10, 2023

    @Ozzcer
    Author

    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

  8. alan-agius4 commented on Nov 10, 2023

    @alan-agius4
    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.

  9. SaeedDev94 commented on Nov 11, 2023

    @SaeedDev94

    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?)

  10. Enngage commented on Nov 12, 2023

    @Enngage

    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?

  11. eneajaho commented on Nov 13, 2023

    @eneajaho
    Contributor

    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.

  12. SaeedDev94 commented on Nov 14, 2023

    @SaeedDev94

    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 ?!

  13. oriollpz commented on Nov 16, 2023

    @oriollpz
  14. 132 remaining items

  15. jhereck commented on Sep 19, 2024

    @jhereck

    Hi any news on that pb pls ?

    Already spend a whole day to search a way to make providers / DI token from SSR server work in client without results : tried with v18.2.5 AND v19.0.0-next.7 (new project to try with the new version), same (no) results.

    My setup :

    Tokens :

    import {InjectionToken} from '@angular/core';
    import {Request, Response} from 'express';
    
    export const REQUEST = new InjectionToken<Request>('REQUEST');
    export const RESPONSE = new InjectionToken<Response>('RESPONSE');
    export const SERVER_TOKEN = new InjectionToken<string>('ServerToken');
    

    Server :

    server.get('**', express.static(browserDistFolder, {
        maxAge: '1y',
        index: 'index.html',
      }));
    
      // All regular routes use the Angular engine
      server.get('**', (req, res, next) => {
        const { protocol, originalUrl, baseUrl, headers } = req;
    
        commonEngine
          .render({
            bootstrap,
            documentFilePath: indexHtml,
            url: `${protocol}://${headers.host}${originalUrl}`,
            publicPath: browserDistFolder,
            providers: [{ provide: APP_BASE_HREF, useValue: baseUrl },
    			{ provide: REQUEST, useValue: req },
              { provide: RESPONSE, useValue: res },
    			{provide: SERVER_TOKEN, useValue: 'TEST TEST'}],
          })
          .then((html) => res.send(html))
          .catch((err) => next(err));
      });
    
      return server;
    }
    

    Component :

    export class AppComponent implements OnInit, OnChanges {
      title = 'angular101';
    
      req!: any
    
      constructor(@Inject(PLATFORM_ID) private platformId: any,
                  @Inject(REQUEST) @Optional() request: Request,
    			  @Inject(SERVER_TOKEN) @Optional() serverToken: String,
    			  @Inject(APP_BASE_HREF) @Optional() appHref: string,) {
    
        if (isPlatformServer(this.platformId)) {
          console.log('SERVER')
    
    		this.req = request.headers
          console.log('REQUEST : ', request.headers)
    		console.log('appHref : ', appHref)
    
    		console.log('serverToken : ', serverToken)
    
    
        } else {
          console.log('CLIENT')
          console.log('REQUEST : ', request?.headers)
    		console.log('appHref : ', appHref)
    		console.log('serverToken : ', serverToken)
        }
    

    I get results in server console, but nothing (null / undefined) in browser console.

    It seems that providers are not transferred to the client, like many others already told.

    Any help would be really appreciated !

  16. aaubry commented on Sep 20, 2024

    @aaubry

    I use a workaround that is not applicable in every situation but may help someone else. This is not a generic solution but allows to read specific headers from the request. In this case it is the cookie, but it should work with other headers as well.

    I have a web server that acts as a reverse proxy for the application. I configured that reverse proxy to take the "Cookie" header and pass it as a query string parameter. I the access the cookie by parsing the URL from PlatformLocation.

    This is the reverse proxy configuration that I use, in this case for IIS. It should be fairly easy to reproduce this with other servers such as nginx.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <location path="." inheritInChildApplications="false">
            <system.webServer>
                <rewrite>
                    <rules>
                        <!-- Remove the 'cookie' parameter from the query string for resources and the vite server -->
                        <rule name="Reverse Proxy new site (files and vite)" stopProcessing="true">
                            <match url="^([^?]+(?:\.\w+|vite/client))" />
                            <action type="Rewrite" url="http://localhost:4200/{R:1}" />
                        </rule>
    
                        <rule name="Reverse Proxy new site (ws)" stopProcessing="true">
                            <match url="^$" />
                            <action type="Rewrite" url="http://localhost:4200/" />
                        </rule>
    
                        <!-- Inject the cookie header as a query string parameter -->
                        <rule name="Reverse Proxy new site and inject cookie" stopProcessing="true">
                            <match url="^(.*)" />
                            <conditions>
                                <add input="{HTTP_COOKIE}" pattern="(.+)" />
                            </conditions>
                            <action type="Rewrite" url="http://localhost:4200/{R:1}?cookie={C:1}" />
                        </rule>
    
                    </rules>
                </rewrite>
            </system.webServer>
        </location>
    </configuration>

    To access the cookie, I use the following code:

    const cookiePrefix = "cookie=";
    const location = inject(PlatformLocation);
    const queryString = location.href.split("?")[1];
    if (queryString) {
        const cookieParam = queryString.split("&").filter(p => p.startsWith(cookiePrefix))[0];
        if (cookieParam) {
            cookieString = decodeURIComponent(cookieParam.substring(cookiePrefix.length));
        }
    }

    Of course that code is only used in development and on the server-side. I use an environment parameter to know which environment the code is running on, and also check isPlatformServer.

  17. 0ba100 commented on Sep 24, 2024

    @0ba100

    Thanks angular team

  18. fluoxa commented on Sep 24, 2024

    @fluoxa

    Thank you very much

  19. shady-ahmed-bdr commented on Sep 24, 2024

    @shady-ahmed-bdr

    angular would be on fire with these updates
    thank you angular team for the effort.
    btw when we will be able to use it next patch ? or V19 ?

  20. alan-agius4 commented on Sep 24, 2024

    @alan-agius4
    Collaborator

    This will only available in v19, which is currently in pre-release.

  21. zygarios commented on Sep 24, 2024

    @zygarios

    Thank you! Finally we'll be able to migrate 💪

  22. kewur commented on Sep 24, 2024

    @kewur

    are there any changes we need to do to get this working on our side?

  23. humanely commented on Sep 24, 2024

    @humanely

    How does this work? Is there a demo script?

  24. jhereck commented on Sep 24, 2024

    @jhereck

    Probably available in next v19 release !

  25. shady-ahmed-bdr commented on Sep 25, 2024

    @shady-ahmed-bdr
  26. angular-automatic-lock-bot commented on Oct 26, 2024

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  27. locked and limited conversation to collaborators on Oct 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions