Skip to content

Angular Universal Roadmap for Angular 4.0 #13822

Closed

Description

@vikerman

Migrate Angular Universal API to @angular/platform-server

High Level Plan

Angular Universal consists of 1)API and 2)tools to do server side rendering of Angular apps. Currently both the Angular Universal API and tools live in angular/universal. The plan is to migrate the API part of Angular Universal to the core Angular project in angular/angular for the Angular 4.0 release and beyond.

We will design the API from ground up to be a core part of Angular and also refactor internals of Angular to better support Angular Universal. The aim is to build a strong foundation for the future development of Angular Universal. This also puts Angular Universal as a core part of Angular and will follow the same quality and release processes as the rest of Angular.

We will keep the API compatible with the current Express wrapper for Universal and make corresponding changes to it as needed. (We haven't scoped out the support for other Universal tools outside of the Express wrapper at this point)

There will be API docs and Dev Guide for Angular Universal. There will be a migration doc to help with migration from the current angular2-universal to the new Angular Universal API.

Use cases

The main use cases we are considering for this iteration of Universal are

  • Initial rendering of Angular application on server for perceived faster loading of application
  • SEO: Content in Angular application is indexed by crawlers
  • Link Preview - Generate a preview of the angular application for link previews on different websites

API

Instead of having a separate Angular platform to support the Universal API we aim to augment the platformServer in @angular/platform-server which already provides the basic support for running Angular in Node.js environment.

Very roughly the usage of this API would look like -

import {platformServer} from '@angular/platform-server';
import {AppServerModuleNgFactory} from './server.ngfactory';
…
// Per Request to avoid cross-talk.
const platform = platformServer([
  {provide: INITIAL_CONFIG, useValue: {
    url: '...',
    document: '...',
  }}
]);

// Long-form rendering
platform
  .bootstrapModuleFactory(MyAppModuleFactory)
  .then((ref: ApplicationRef) => ref.isStable.filter(v => v).toPromise())
  .then(() => platform.injector.get(PlatformState).renderToString())
  .then(html => ...)
  .then(() => platform.destroy());

The two main options to be passed in are the document string which represents the whole document from what would be the index.html on the client side app and the current app URL. These are specified through the INITIAL_CONFIG provider on the platform.

There will be a convenient API for the most common use case of bootstrapping and rendering a single application -

Import {renderModuleFactory, renderModule} from '@angular/platform-server'

// Short-form rendering
renderModuleFactory(MyAppModuleFactory, {url: '...', document: '...', providers: [..]}).then(html => …);

The other main addition will be the ServerModule in @angular/platform-server that corresponds to the BrowserModule in the client side. We recommend that you have a separate top-level App Browser Module and an App Server Module where you specify your platform specific providers including BrowserModule and ServerModule respectively.

Any extra data to be passed in to the server application will be done through providers.

Implementation details

  • Keep the current implementation of the renderer in platformServer and make changes to it as needed to support Universal use cases.

  • Refactor Http module to be platform independent and move the platform dependent parts into platformBrowser and platformServer.

  • Provide a server side Location service.

  • Use the current Metatags service for any met tags manipulation required for link previews.

  • We will make the server implementation of Http(most probably based on XHR2) on the server platform to be Zone aware. We will provide guidelines on how to make other asynchronous Node libraries Zone aware - so that the server side application knows when the rendering is actually complete.

  • Provide a way to test Universal ready Components and Application. We already run all internal Angular tests in the Node environment. We will provide helper utilities to make it easier to test your Universal ready Components on both Node and browser.

  • Update the Universal starter to use the new API

Thanks,
Vikram Subramanian and Alex Rickabaugh

Activity

  1. added this to the milestone on Jan 7, 2017
  2. MarkPieszak commented on Jan 7, 2017

    @MarkPieszak

    Just wanted to make sure @gdi2290's notes on the Universal integration were in as well from #12495 (comment)

    One thing to note when dealing with ASP.NET Core environment for example, we typically won't be given the entire html document, rather just a fragment such as the root <app></app> for example since .NETs MVC handles the (.cshtml file, which in turn becomes the .html file during rendering). This might create some issues when trying to integrate the Metatags service.

    Just wanted to make sure it's on the radar, here's an example of .NET & Universal in action:

    /* ... imports ... */
    const platform = platformNodeDynamic();
    
    export default createServerRenderer(params => {
        return new Promise<RenderResult>((resolve, reject) => {
            const requestZone = Zone.current.fork({
                name: 'angular-universal request',
                properties: {
                    baseUrl: '/',
                    requestUrl: params.url,
                    originUrl: params.origin,
                    preboot: false,
                    document: '<app></app>'     // <------- ** 
                },
                onHandleError: (parentZone, currentZone, targetZone, error) => {
                    // If any error occurs while rendering the module, reject the whole operation
                    reject(error);
                    return true;
                }
            });
    
            return requestZone.run<Promise<string>>(() => platform.serializeModule(AppModule)).then(html => {
                resolve({ html: html });
            }, reject);
        });
    });
    

    Open issue: Do we provide a way to pass in the request data to the server side Angular application in the first iteration?

    @vikerman Are you talking about the req object from Node? (https://github.com/angular/universal-starter/blob/master/src/server.ts#L72-L82)

    Also would love to help with the integration in any way 📦

  3. FrozenPandaz commented on Jan 7, 2017

    @FrozenPandaz
    Contributor

    We are already using a copy of the Metatags service in our Universal App and it is already agnostic, we just had to transfer state by querying the DOM onInit on client side.

    Also as a compliment to this, what is the roadmap for CLI integration for Universal? Maybe the Universal Starter should be rebased to an Angular CLI / Universal CLI generated app?

    I would also like to help in anyway possible.

  4. vikerman commented on Jan 7, 2017

    @vikerman
    ContributorAuthor

    @MarkPieszak - Thanks for the pointers. We are working with Patrick on this. Alex and I did discuss about having separate document and fragment fields in the platformServer options to support other use cases where you don't control the whole document. I will put up the proper proposed signatures of each of these APIs to the bug soon. We are still in the process of reviewing the API with rest of the team.

    @FrozenPandaz - If the Metatags service is already working in a platform agnostic way then it's just a matter of moving it to a place that reflects that. CLI needs to have the required extension mechanism to support Universal and is definitely in our radar post-4.0.

    The aim of this is to provide a solid API foundation for Universal. We can definitely use your help in getting feedback on use cases and integrations with the current set of tools around Universal.

  5. FrozenPandaz commented on Jan 7, 2017

    @FrozenPandaz
    Contributor

    @vikerman would I be able to assist with moving it? I gave it a shot and the bigger underlying issue is that it relies on the DomAdapter which is currently native to @angular/platform-browser.. Should that be moved to @angular/common as well? That seems to require more refactoring.

  6. MarkPieszak commented on Jan 26, 2017

    @MarkPieszak

    @vikerman @gdi2290 @alxhub @SteveSandersonMS

    To go along with my comment about manipulating <title> & <meta> that's outside of the Angular application (such as how we need it to work for .NET, and I imagine other integrations might be similar).

    Could I propose a slightly different (or optional) syntax for the serializer, one that doesn't just return the html, but also optional metatags information that could be used outside of Angular and applied where needed?

    import {platformServer} from ‘@angular/platform-server’;
    import {AppServerModuleNgFactory} from ‘./server.ngfactory’;
    
    platformServer({
      document: ‘<app></app>’, // <-- .NET we only pass the application itself (it controls the <html>/etc)
      // ...
    }).renderModuleFactory(AppServerModuleNgFactory)
        .then(result => 
            let html = result.html;
            let meta = result.meta; // <--- title/meta/ basically anything external data you want to expose
         );
    

    You can see we are discussing this (aspnet/JavaScriptServices#607), and the necessary changes on the .NET side that would need to take place. But without something like this, there isn't a very clean way of abstracting out this information. Currently I am storing all Title/Meta information on route changes / loads onto the window object and then searching through the html result to put it all back together.

    Let me know what you guys think, just throwing ideas around!

  7. hheexx commented on Feb 1, 2017

    @hheexx

    Any progress? How it's going?
    It should be RC time today :)

  8. shawnsz commented on Feb 6, 2017

    @shawnsz

    I don't want to intrude but I really need the Angular Universal support for Angular 2.4 or Angular 4. From the official release schedule, there's no enough time left. I guess there's no breaking changes during the release candidate stage. So is it possible to include the universal merge code to Angular 4 or should we give up the hope and wait until Angular 5 release? An update would be great. Thanks!

    From the official release schedule:
    2017-02-08 2.4.7 4.0.0-rc.0
    2017-03-08 4.0.0 + 2.4.11 - Major Version Release

  9. poiati commented on Feb 7, 2017

    @poiati

    Yes, we know that this is a free opensource project (backed by Google and the community) and we aren't in position to demand anything but a status update from the core devs would be really appreciated.

    Thanks and keep the good work.

  10. jbrantly commented on Feb 7, 2017

    @jbrantly

    Looks like the RC date has been pushed to Feb 15: #14341

  11. vikerman commented on Feb 7, 2017

    @vikerman
    ContributorAuthor

    Sorry for keeping everyone on suspense as we were trying to sort out the internal timing. Yes - The RC0 date is the 15th and we are targeting the Universal API changes in core for that.

    This is the final design doc for the API - https://docs.google.com/document/d/1eGEq0N7czS8nWWuCV3n4eMF3GFzk88rsN0bll6yE0bE/edit#heading=h.mzv58ip927vv. I am in the process of updating the issue above with the latest info.

  12. berndartmueller commented on Feb 9, 2017

    @berndartmueller

    @vikerman thanks for sharing the final design doc.

    I have one very important question about SEO. Right now Angular 2 needs to re-render on the client after receiving the server-side rendered view (from universal) and replacing the ssr view with the newly rendered view from the client. In between the user is not able to use the app at all, because it's simply not interactive. To somehow fix this problem, preboot was introduced to simply replay previous events. With the current re-render and buffer approach I see two major problems.

    1. It has major implications on page interactivity and therefore the actual usability of a page (note: this might also be more of an issue on less hardware heavy mobile devices)

    2. It's almost impossible for an intermediate sized app to hit the recommended performance guidelines from Google for SEO (TTFB: 200ms, Start render: 700ms, Finished render above fold: 1000ms) due to a complete re-render of the app.

    Is there any focus on using something like a DOM hydration approach (#13446)? Or are there any improvements planned? Depending on your answer I have to evaluate if Angular (Universal) is a good fit to our technology stack and our SEO requirements.

  13. FrozenPandaz commented on Feb 9, 2017

    @FrozenPandaz
    Contributor

    @vikerman Thank you for sharing the design docs. Can we have a way to filter issues by this feature and also can you scope out the issues/ tasks that need to be accomplished to make this happen? Maybe you can just mention this issue in related issues so that we can see a list here? I would like to help out.

    EDIT: Found label:"comp: server" but no issues open with that yet

  14. 57 remaining items

  15. shawnsz commented on Mar 28, 2017

    @shawnsz

    Hi all. Is there any document/sample code showing how to do pre-rendering by calling renderModuleFactory to get the HTML pages? Angular 4 is out but still no enough document.

  16. somombo commented on Mar 29, 2017

    @somombo

    I am interested in how all this affects the Mobile-toolkit Project.

    Correct me if I'm wrong, but it seems that the mobile-toolkit was stagnated, in part, by dependency on angular-cli (--mobile flag removed) and angular-universal (used for app-shell).

    So now that @angular/platform-server merged the angular-universal core.. I am curious about the future of the mobile-toolkit.

    I haven't seen any new commits or updates to the angular-universal repo since the platform-server update. Is the angular-universal repo/project discontinued? If so, does that mean the mobile-toolkit is as well?

    Thanks

    cc: @MarkPieszak @gdi2290 @alxhub @jeffbcross @hansl @filipesilva @robwormald

  17. linusbrolin commented on Apr 6, 2017

    @linusbrolin

    Hi, I've tried to find how to make localStorage work when using Universal/platform-server?
    I get an error message that localStorage is not defined when I try running my app.
    I've checked #7438 angular/universal#309 angular/universal#247 angular/universal#272 and angular/universal-starter#80 but nowhere does it say if a Storage Service has been implemented, how to use it, or how to avoid the problem.

    Does anyone know?

  18. ozknemoy commented on Apr 6, 2017

    @ozknemoy

    try this

    `export class LocalStorage {
    storageKeyPrefix = 'ngStorage-';
    storageType = 'localstorage';
    constructor(@Inject('isBrowser') public isBrowser ) {}

    get(key) {
        if (this.isBrowser) {
            return (window.localStorage.getItem(this.storageKeyPrefix + key));
        } else {
            return this[key]
        }
    };
    
    set(key, value) {
        if (this.isBrowser) {
            window.localStorage.setItem(this.storageKeyPrefix + key, value)
        } else {
            this[key] = value
        }
    };
    

    }`

  19. fulls1z3 commented on Apr 26, 2017

    @fulls1z3

    Just released a cache utility for Angular working on both browser and server platforms, and explained the local storage on angular/universal#272 and on fulls1z3/universal#5.

    Writing the documentation now, but you can have a look at ng-seed/universal for its usage.

    Check the implementation: just updated this repo as well as publishing 4 separate packages for cache operations both on server and browser platforms. Everything is handled via the @Cached(...) decorator on the method/loader/etc which you want it cached. Also, there's the possibility to use caching methods (has, get, set) using the caching API.

    You might ask why to keep the structure so complex and consume 4 different packages? The answer is, not all the use cases depend on caching on the server platform. Furthermore, this structure allows to integrate any kind of custom caching with the server or browser platform (ex: session, api, etc).

    Currently there's no documentation available for these packages, because these days I'm kinda overloaded with many different tasks/projects. I think in a week or two I'll try to provide a good documentation as well as unit tests for these packages.

    However, try to have a look on this repo - about the use of CacheService and its instruments. I think it won't be difficult to understand the concepts, as I've kept the code style as DRY as possible.

  20. mohamed-rekiba commented on May 3, 2017

    @mohamed-rekiba

    @fulls1z3
    good job, just need watch & serve options

  21. jerbes commented on May 3, 2017

    @jerbes

    Is there a good place to get official current benchmarks?
    We are currently using angular 1 and would like to make the case for angular 4.

  22. SystemDisc commented on Sep 19, 2017

    @SystemDisc

    How do we get the "req" object in a component during SSR? How do we get cookies sent from the user's browser to NodeJS (ExpressJS) during SSR? Is there a way to passthrough cookies/headers when making HTTP requests during SSR?

    I feel like if a browser requests a page, SSR should load the cookies/headers passed, and pass them to HttpClient and whatnot.

    Edit: nevermind, I figured it out: #15730 (comment)

  23. Toxicable commented on Sep 19, 2017

    @Toxicable

    @SystemDisc If you're using ngExpress Engine then you can simply inject the request like so https://github.com/angular/universal/tree/master/modules/ng-express-engine#using-the-request-and-response

  24. SystemDisc commented on Sep 19, 2017

    @SystemDisc

    @Toxicable Thanks! I'm not using ngExpress Engine, but I figured it out using extraProviders: #15730 (comment)

    The comment I linked to is also relevant to @kukjevov and other users trying to pass cookies/auth during SSR

  25. ranjitnadar commented on Dec 1, 2017

    @ranjitnadar
  26. angular-automatic-lock-bot commented on Sep 13, 2019

    @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 Sep 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions