Skip to content

Angular Hydration not working in production build. #54477

Closed as not planned
Closed as not planned

Description

@princ09

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

Don't known / other

Is this a regression?

Yes

Description

I have basic development & production configuration like below,

    "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "3mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "4kb",
                  "maximumError": "1mb"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "optimization": false,
              "extractLicenses": false,
              "sourceMap": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.development.ts"
                }
              ]
            }
          },
          "defaultConfiguration": "production"
        },
"scripts": {
    "ng": "ng",
    "start": "ng serve --port=4444 -o",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "serve:ssr:ser_test": "node dist/srr_test/server/server.mjs"
  },

It seems like when you run npm run build followed by npm run serve:ssr:ser_test, hydration isn't functioning properly, evidenced by flickering. However, in development mode (npm run start), the flickering issue is less pronounced, although still present.

Moving the configurations below into the production config:

"optimization": false,
"extractLicenses": false,
"sourceMap": true

resolves the hydration issue in the production build. It appears that the optimization flag might be the culprit, as enabling it causes the issue to resurface. Despite the hydration not fully working, it's crucial to address this issue. Could there be something overlooked in this setup?

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

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

Angular CLI: 17.1.0
Node: 21.4.0 (Unsupported)
Package Manager: npm 10.2.4
OS: darwin arm64

Angular: 17.1.0
... animations, cdk, cli, common, compiler, compiler-cli, core
... forms, material, platform-browser, platform-browser-dynamic
... platform-server, router, ssr

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1701.0
@angular-devkit/build-angular   17.1.0
@angular-devkit/core            17.1.0
@angular-devkit/schematics      17.1.0
@schematics/angular             17.1.0
rxjs                            7.8.1
typescript                      5.2.2
zone.js                         0.14.3

Anything else?

No response

Activity

  1. AndrewKushnir commented on Feb 17, 2024

    @AndrewKushnir
    Contributor

    @princ09 unfortunately, the information that you provided is not sufficient to perform further investigation, but here are a couple things that you can check:

    • Make sure hydration is enabled (the provideClientHydration() call is present in the app config), see here for additional info. Based on the description of the problem (the flickering behavior), I suspect that this might be the case.
    • Check if you have any warnings/errors in dev console in your browser. Error messages might contain useful info on what the issue is.

    If the problem still exists, please create a minimal repro (only relevant code and minimal possible setup, please do not share the whole app) in a form of GitHub repository, so that we can perform further investigation.

  2. added
    needs reproduction
    area: core
    on Feb 17, 2024
  3. modified the milestone: Backlog on Feb 17, 2024
  4. princ09 commented on Feb 17, 2024

    @princ09
    Author
    • see here

    @AndrewKushnir
    I already have followed everything mentioned in the docs, Please refer below,

    1. Added provideClientHydration() in providers of AppModule.
    import { LOCALE_ID, NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { UrlpartPipe } from './common/pipes/urlpart.pipe';
    
    import { BrowserModule, provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
    import { AppRoutingModule } from './app-routing.module';
    import { NoopAnimationsModule } from '@angular/platform-browser/animations';
    import { MatTabsModule } from '@angular/material/tabs';
    import { MAT_RIPPLE_GLOBAL_OPTIONS, RippleGlobalOptions } from '@angular/material/core';
    import { NavbarComponent } from './common/components/navbar/navbar.component';
    import { HttpClientModule, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
    import { AuthService } from './common/services/auth.service';
    import { errorHandleInterceptor } from './common/interceptors/error-handle.interceptor';
    import { DecimalPipe } from '@angular/common';
    
    const globalRippleConfig: RippleGlobalOptions = {
      disabled: true,
      animation: {
        enterDuration: 0,
        exitDuration: 0
      }
    };
    @NgModule({
      declarations: [
        AppComponent,
        NavbarComponent,
        UrlpartPipe,
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        NoopAnimationsModule,
        MatTabsModule,
        HttpClientModule
      ],
      providers: [
        DecimalPipe,
        {provide: MAT_RIPPLE_GLOBAL_OPTIONS, useValue: globalRippleConfig},
        provideHttpClient(
          withFetch(),
          withInterceptors([errorHandleInterceptor]),
          withFetch()
        ),
        provideClientHydration(withHttpTransferCacheOptions({
          includePostRequests: true
        })),
        AuthService
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    1. Added provideClientHydration() in providers of AppServerModule (Not Required I know but it doesn't matter).
    import { NgModule } from '@angular/core';
    import { ServerModule } from '@angular/platform-server';
    
    import { AppModule } from './app.module';
    import { AppComponent } from './app.component';
    import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
    
    @NgModule({
      imports: [
        AppModule,
        ServerModule,
      ],
      bootstrap: [AppComponent],
      providers: [
        provideClientHydration(
          withHttpTransferCacheOptions({
            includePostRequests: true,
          }),
        ),
      ]
    })
    export class AppServerModule {}
    
    import { APP_BASE_HREF } from '@angular/common';
    import { CommonEngine } from '@angular/ssr';
    import express from 'express';
    import { fileURLToPath } from 'node:url';
    import { dirname, join, resolve } from 'node:path';
    import AppServerModule from './src/main.server';
    const compression = require('compression');
    import { caching } from 'cache-manager';
    
    
    // The Express app is exported so that it can be used by serverless Functions.
    export async function app(): Promise<express.Express> {
      const server = express();
      const memoryCache = await caching('memory', {
        max: 100,
        ttl: 10 * 1000 /*milliseconds*/,
      });
    
      const ttl = 5 * 1000; /*milliseconds*/
    
      server.use(compression({ level: 8 }));
      const serverDistFolder = dirname(fileURLToPath(import.meta.url));
      const browserDistFolder = resolve(serverDistFolder, '../browser');
      const indexHtml = join(serverDistFolder, 'index.server.html');
    
      const commonEngine = new CommonEngine();
    
      server.set('view engine', 'html');
      server.set('views', browserDistFolder);
    
      // Example Express Rest API endpoints
      // server.get('/api/**', (req, res) => { });
      // Serve static files from /browser
      server.get('*.*', express.static(browserDistFolder, {
        maxAge: '1y'
      }));
    
      // All regular routes use the Angular engine
      server.get('*', (req, res, next) => {
        const { protocol, originalUrl, baseUrl, headers } = req;
    
        commonEngine
          .render({
            bootstrap: AppServerModule,
            inlineCriticalCss: false,
            documentFilePath: indexHtml,
            url: `${protocol}://${headers.host}${originalUrl}`,
            publicPath: browserDistFolder,
            providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
          })
          .then((html) => res.send(html))
          .catch((err) => next(err));
      });
    
    
      return server;
    }
    
    async function run(): Promise<void> {
      const port = process.env['PORT'] || 4000;
    
      // Start up the Node server
      const server = app();
      (await server).listen(port, () => {
        console.log(`Node Express server listening on http://localhost:${port}`);
      });
    }
    
    run();
    
    1. Added initialNavigation as well in RoutingModule.
    @NgModule({
        imports: [RouterModule.forRoot(routes, {
            preloadingStrategy: PreloadAllModules,
            useHash: false,
            scrollPositionRestoration: 'enabled',
            initialNavigation: 'enabledBlocking'
        })],
        exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    In fact I am getting this message in console as well,
    Angular hydrated 17 component(s) and 158 node(s), 0 component(s) were skipped. Learn more at https://angular.io/guide/hydration.

    Please see the recording of how it's flickering ,
    screen-capture.webm

    Let me know If I am missing something,
    Thanks

  5. AndrewKushnir commented on Feb 17, 2024

    @AndrewKushnir
    Contributor

    @princ09 thanks for providing more info. Based on the console message, hydration was enabled and actually worked. Based on the screen recording - this flickering happens due to the external font loading delay. The solution would be to optimize font loading (use a smaller font, add preconnect/preload tags, etc).

    Unrelated to font loading, but you can also drop initialNavigation: 'enabledBlocking' - that is no longer required when hydration is enabled.

  6. princ09 commented on Feb 19, 2024

    @princ09
    Author

    @AndrewKushnir Thank you for your reply. After removing the font-display property it solved the font issue but the hydration issue is still there. I have created a git repo for you here. I have enabled hydration.
    See in screenshot, I got the message as well,
    Screenshot 2024-02-19 at 1 27 19 PM
    But still flickering issue is there, please check the video
    screen-capture (2).webm

  7. AndrewKushnir commented on Feb 20, 2024

    @AndrewKushnir
    Contributor

    @princ09 thanks for additional info and creating a repro.

    I took a look and found out that hydration works correctly - most of the nodes on a page got hydrated (vs being re-created from scratch).

    I've also noticed that navigating to a different page in your test app causes a full page reload. As a possible option to improve the navigation experience, you can try to use view transitions feature. You can enable it by doing this change:

    diff --git a/src/app/app.config.ts b/src/app/app.config.ts
    index e5a3cf1..7c8a415 100644
    --- a/src/app/app.config.ts
    +++ b/src/app/app.config.ts
    @@ -1,9 +1,9 @@
     import { ApplicationConfig } from '@angular/core';
    -import { provideRouter } from '@angular/router';
    +import { provideRouter, withViewTransitions } from '@angular/router';
     
     import { routes } from './app.routes';
     import { provideClientHydration } from '@angular/platform-browser';
     
     export const appConfig: ApplicationConfig = {
    -  providers: [provideRouter(routes), provideClientHydration()]
    +  providers: [provideRouter(routes, withViewTransitions()), provideClientHydration()]
     };
    

    You can also try using the RouterLink directive to enable client navigations (without a full page reload) to see if that works better for you. Here is a diff that I've made to use the RouterLink for the Home and About links (so you can navigate between those pages to test the behavior):

    diff --git a/src/app/app.component.html b/src/app/app.component.html
    index 25e85e0..956ff3a 100644
    --- a/src/app/app.component.html
    +++ b/src/app/app.component.html
    @@ -12,13 +12,13 @@
         <div class="collapse navbar-collapse" id="navbarCollapse">
           <ul class="navbar-nav mx-auto">
             <li class="nav-item">
    -          <a class="nav-link" aria-current="page" href="https://github.com/">
    +          <a class="nav-link" aria-current="page" [routerLink]="['/']">
                 <i class="fas fa-home me-1"></i>Home</a>
             </li>
           </ul>
           <ul class="navbar-nav me-auto">
             <li class="nav-item">
    -          <a class="nav-link active" aria-current="page" href="https://github.com/about">
    +          <a class="nav-link active" aria-current="page" [routerLink]="['/about']">
                 <i class="far fa-question-circle me-1"></i>About</a>
             </li>
             <li class="nav-item">
    

    Based on the investigation results, it looks like hydration works as expected and there are no action items for the framework, so I'll close the ticket for now. Please reopen or create a new one if you come across an issue caused by the framework logic.

  8. princ09 commented on Mar 11, 2024

    @princ09
    Author

    Sorry @AndrewKushnir, I wasn't available for the last few weeks. Unfortunately, this solution is not a solution in my perspective because of two reasons.

    1. If I use routerLink then it won't be SSR at all, It will be SPA.
    2. I can't use routerLink because it's not good for SEO, I need full page load.

    Please have look into this amazing ssr website Dhan.co , here every link is href and whole page get rendered from server. I believe they used react with next.js, I am looking for similiar result from angular 17.

  9. AndrewKushnir commented on Mar 11, 2024

    @AndrewKushnir
    Contributor

    @princ09 thanks for additional info. You don't have to use routerLink, the hydration works on your demo correctly after a page refresh.

    You can still try to use withViewTransitions() as described above to improve transitions between pages.

  10. angular-automatic-lock-bot commented on Apr 11, 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.

  11. locked and limited conversation to collaborators on Apr 11, 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

    Labels

    area: corecore: hydrationneeds reproduction

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions