angular: Angular SSR not updating dynamic meta tags and content received from API

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

platform-server

Is this a regression?

Yes

Description

I’m working on an Angular SSR application and I’m facing a problem when updating Open Graph meta tags after receiving content from the API, as in another component that updates directly (without consuming the API) there is no problem. Although when viewing elements in the page source code, all meta tags are updated. The problem is that when sharing, they don’t show the updated meta tags.

After I updated to Angular 17 it stopped working, but I’m not sure, because it was in some version that it stopped working and I had made several Angular updates.

Please provide a link to a minimal reproduction of the bug

Unfortunately, I have no way of reproducing the error for you to analyze, as the error only occurs in production and cannot be reproduced in stackblitz.

Please provide the exception or error you saw

ngOnInit(): void {
  this.metadataService.removeTags(); // Removing existing tags

  // ... (other initialization code)

  if (this.reNumber.test(sumarioId) && Number(sumarioId) > 0) {
    this.artigoService.GeArticle(sumarioId).subscribe({
      next: (res: Artigo) => {
        if (res != null) {
          this.artigo = res;
          // ... (other processing)
          this.updateMetaDataArticle();
        }
      },
      // ... (error and complete handlers)
    });
  }
}


private updateMetaDataArticle(): void {
  let meta: PageMetaData = new PageMetaData();
  // ... (other meta data setup)

  meta.title = this.artigo?.manuscriptTitle as string;
  meta.description = this.artigo?.abstract as string;

  if (this.metadataService) {
    this.metadataService.updateMetadata(meta);
    // ... (other actions)
  }
}

public updateMetadata(metadata: Partial<PageMetaData>): void {
  // ... (other metadata updates)
  this.metaTagService.addTags([
    { property: 'og:title', content: metadata.title },
    { property: 'og:description', content: metadata.description }
    // ... (other meta tags)
  ], false);
}

public removeTags(): void {
  if (!this._platform.isBrowser) return; // Avoid processing during server-side rendering

  this.metaTagService.removeTag('property="og:title"');
  this.metaTagService.removeTag('property="og:description"');
  // ... (other tag removals if relevant)
}

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

Angular CLI: 17.0.8
Node: 20.10.0
Package Manager: npm 10.2.5
OS: win32 x64

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

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1700.8
@angular-devkit/build-angular   17.0.8
@angular-devkit/core            17.0.8
@angular-devkit/schematics      17.0.8
@angular/cdk                    17.0.4
@angular/material               17.0.4
@schematics/angular             17.0.8
rxjs                            7.8.1
typescript                      5.2.2
zone.js                         0.14.2

Anything else?

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 62 (13 by maintainers)

Most upvoted comments

@hieutranagi47 I am also facing the same problem. one thing I can tell something has happened after Angular version 17.0.3. I have an application that uses Angular 17.0.3, when I share the URL of my application to social media like Twitter or Facebook, it renders the dynamic meta tags correctly. But my other application which is running on angular 17.2.1, URLs are not working on social media sites. it renders the default value of the meta tags. Example of app running on 17.03 ( dynamic meta tags working) : https://contentbuffer.com/issues/news/technical/telegram-now-lets-users-convert-personal-accounts-business-accounts Example of app running on 17.2.1 ( dynamic meta tags not working): https://codebrainery.com/article/navigating-ai-revolution-software-development-chatgpt

@shivamsharma01 can’t help you but yes, I had it working with Angular 11 and Ionic 5.

If your meta tags aren’t updated it’s likely that your app become stable before they are set. Keep in mind that SSR/SSG works as following : The HTML will be generated until the first time the app becomes stable (ApplicationRef.isStable). Once the app becomes stable the HTML is sent to the client and nothing else will happen to the pre-generated content and the hydration process takes over on the client.

I’ll be happy to take a look if you’re able to provide a narrowed down reproduction (either stackblitz or a github repo is fine).

@JeanMeche Could you Please reopen this issue…we still don’t have the solution for this. My angular app is running on AWS with nginx and SSR. Still meta tags are not getting updated dynamically, it loads the default tags

@liamong0422 if you need to load meta-data from an API, you should use resolvers:

const title = 'My Pizza place';
const seoResolver: ResolveFn<NgxSeo> = (route, state) => {
  return inject(MenuService)
    .getItemByUUID(route.params['itemUUID'])
    .pipe(
      map((item: MenuItem) => {
        return {
          title: route.params['itemUUID'] ? item.name : 'Menú | ' + title,
          meta: {
            description: route.params['itemUUID']
              ? item.description
              : 'Best pizza in town',
            image: item.imageUrl,
            type: 'website',
            url: 'https://mypizzaplace.com' + state.url,
          },
        };
      }),
    );
};

export const MENU_ROUTES: Routes = [
  {
    path: ':itemUUID',
    component: MenuComponent,
    resolve: { seo: seoResolver },
  }
  {
    path: '',
    component: MenuComponent,
    resolve: { seo: seoResolver },
  },
];

I’m already using the resolver but I am still experiencing the same issue. The website will load the home page first, then to the details page. But for pages that doesn’t load API, it will go straight to the page and the metatags were successfully loaded in the page source.

Yes, it works with angular 17

On Wed, 3 Apr 2024, 01:37 Sebastián Rojas Ricaurte, < @.***> wrote:

@codewithbisky https://github.com/codewithbisky works with Angular 17?

— Reply to this email directly, view it on GitHub https://github.com/angular/angular/issues/53711#issuecomment-2033284528, or unsubscribe https://github.com/notifications/unsubscribe-auth/BCC6WIWBIFKUVIQOS2DI3QTY3M6NNAVCNFSM6AAAAABBEZVDFWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDAMZTGI4DINJSHA . You are receiving this because you were mentioned.Message ID: @.***>

This is how I solved this. I created a ItemResolver and added it into my routes

`import { Injectable } from ‘@angular/core’; import { Resolve, ActivatedRouteSnapshot } from ‘@angular/router’; import {ItemService} from “…/service/item.service”;

@Injectable({ providedIn: ‘root’ }) export class ItemResolver implements Resolve<any> { constructor(private dataService: ItemService) {}

async resolve(route: ActivatedRouteSnapshot) {
    const id = route.paramMap.get('id') ?? '';
    return await this.dataService.getItemPublicPromise(id);
}

}`

This is route configuration

{path: 'view-video/:id', component: ViewVideoPageComponent, resolve: { resolvedData: ItemResolver }},

I did this in onNit of ViewVideoPageComponent

`imageUrl: string = ‘’; item: any ; ngOnInit(): Promise<void> { this.item = this.resolvedData = this.route.snapshot.data[‘resolvedData’]; this.imageUrl = your_domain+this.item.imagePath;

    this.updateMeta();

}

private updateMeta() {

    this.ngxSeoService.setSeo({
        title: this.item.title,
        meta: {
            description: this.item.metaDescription,
            image: this.imageUrl,
            type:"website"
        },
    });
}
`
I am using this dependency
"@avivharuzi/ngx-seo": "^16.0.0",


Everything is working. It is not showing the thumbnail on whatsapp. If you solve whatsapp let me know

Example of this is this one https://www.codewithbisky.com/view-video/2b3fae4d-8e75-4d50-b9b0-e50857e2e83c

@leandrotassi: I have these 2 applications both are running on the same setup and server. One is working and other one is not. Example of the app running on 17.03 ( dynamic meta tags working) : https://contentbuffer.com/issues/news/technical/telegram-now-lets-users-convert-personal-accounts-business-accounts Example of app running on 17.2.1 ( dynamic meta tags not working): https://codebrainery.com/article/navigating-ai-revolution-software-development-chatgpt

@hieutranagi47 Your issue is that you’re not using SSR but prerendering (SSG). (ng-server-context="ssg" attribute in the DOM) Check the output build and particularly prerendered-routes.json, it contains only

{
  "routes": [
    "/",
    "/post"
  ]
}

You app isn’t prerendering each post entry which explains why the meta still contains the placeholder.

@roosikem @monacodelisa @yogeshbansal : While we are waiting for the fix from the Angular core team, we could try the pre-render feature of Angular CLI. I tested it and it works. https://angular.io/guide/prerendering#prerendering-parameterized-routes

If you notice, you will see that Angular renders the root route (“/”), before render the actual route.

@hieutranagi47 I am also facing the same problem. project is working locally but in production it is not working. meta tags are not updating and not able to working in social media (not displaying correct meta tags and images, showing only default tags)

@kodetratech I don’t know the root cause of the issue in this case, Angular renders the home page first, then switch to the post detail page although I access the post detail page. I guess that it’s Angular issue, so I don’t know what the best solution for this should be. If your page calls only one API => There is no problem.