Universal: Proper redirects with status codes (SEO reasons)

Created on 12 Oct 2017  路  3Comments  路  Source: angular/universal

  • I'm submitting a ...
- [x] feature request
  • What modules are related to this Issue?
- [x] aspnetcore-engine
- [x] express-engine
- [x] hapi-engine
  • Do you want to request a feature or report a bug?
    Request a feature

  • What is the current behavior?
    Currently, if we have a redirectTo in our route config or router.navigate or router.navigateByUrl in our code, Universal renders the appropriate component, but doesn't actually do a redirect.

  • What is the expected behavior?
    Given a redirectTo in our route config or router.navigate/navigateByUrl anywhere in our code, Universal should actually redirect to the appropriate route.

  • What is the motivation / use case for changing the behavior?
    For SEO reasons. We wouldn't want to render content on "wrong" route.
    Ideally, the @angular/router should also facilitate a way to let Universal know what status code is needed (but that would be an issue for the router).

  • Please tell us about your environment:

  • Angular version: 4+

  • Platform: [NodeJs]

Most helpful comment

@MrCroft please check https://github.com/patrickmichalina/fusebox-angular-universal-starter/blob/master/src/client/app/app.component.ts

It listen for data.response in router-module configurations to apply cache settings to the given route. I will make this a module in the future, but can give you some ideas - similar to what @PsychicCat is saying

All 3 comments

You should be able to do this already by importing the RESPONSE token from 'nguniversal/express-engine/tokens' then injecting that into an Angular service which subscribes to the router events. I would then filter for NavigationEnd, and then check if the urlAfterRedirects is different from the url. If so, set the response code to 302 and set header location.

The same premise can be applied to actual 404, 500, whatever status code you want to send on server render.

Edit: you can see how to access the express response object here:
https://github.com/angular/universal/issues/667

@PsychicCat I was just thinking that, for core methods, the desired way would be to be handled by Universal by default (like when you inject the router and use this.router.navigate() or this.router.navigateByUrl()).
The less we have to clutter the code with our own logic, the better.

@MrCroft please check https://github.com/patrickmichalina/fusebox-angular-universal-starter/blob/master/src/client/app/app.component.ts

It listen for data.response in router-module configurations to apply cache settings to the given route. I will make this a module in the future, but can give you some ideas - similar to what @PsychicCat is saying

Was this page helpful?
0 / 5 - 0 ratings