angular universal server-side rendering- Easy project setup with angular 6/7 cli
Articles,  Blog

angular universal server-side rendering- Easy project setup with angular 6/7 cli


hi there this is Kalyan from Black
Box Tech today I’m going to discuss about angular Universal which the nickname is
sometimes called by different peoples or angular’s a ssr or server-side
rendering so what is angular server-side rendering so as you know like you
already used angular client-side rendering using angular cli
basically server-side rendering will help you to render your application from
server you know like when you installed a or generated project using angular cli it is generated and when you run into the browser actually browser takes
care of everything but there are some problems so when it
comes to SEO or search engine optimizations Google don’t know actually
if what you are what need to crawl or because it’s an ajax website so if you
remember in the previous generation when you create an ajax based application
it’s generally there are some difficulty crawling your site by Google so mitigate
that issue actually angular comes up with angular server side rendering
technology where it’s completely compile your application or generate your
complete HTML or if you fragment as a string in the server and it then bring
us from the server so there are two times bootstrap one is from server and another
is one client and thus it’s makes your application
specially available to the different crawlers and make its search engine
optimized application and also it is really helpful it’s actually better
performance you will create by using angular universal. So let’s
get started let’s start by creating an angular cli application to do that you need you need angular cli installed in your
system I am assuming that you already have that if not you can install it
quickly by running this command npm install @angular/cli -g and then install and then you know and you need
to install it globally I already installed that in my system so I am NOT
going to install it again so now I am just changing my directory to desktop
and using this command ng new and provide a project name you can generate and
I’m gonna say like application it will prompt you for few of the questions you
can also ask for your choice and we’ll take some moment to generate this
completed application once it completes our we just opened
this project inside Visual Studio code to convert these angular CLI client-side
application to an angular server-side rendering project you need to create
few files as well as you need to update new existing files so to
save some time I am going to use another tool which called angular console it
will help you to generate the necessary files except few one which you can
create by your own so for example within this application you can actually just
so your existing application but will automatically load it and then by
selecting this you can select that Universal application now it will last
few of the questions so the name of the project we have given an SSR and then
all of the details will be same not literally once it’s done close it now let’s see
what all things has been updated and created so you can see it modifies the
package torjussen let’s see what is added so it’s added or
gonna HTTP it something only they’re not sure why it’s added again the second
thing which added is the platform server which is a very important model for
angular Universal next it’s also modified the angular torjussen
and it’s added this summer block so what is that so it’s saying the bender to
build your application it will use angular date field and the output of
your son were rendered file will be inside this is a surf server so you can
actually change this name as for your test so I want of my server project or
files when that files will be inside this and inside a folder called circle
the main file it is pointing to so main dots on board or TS
and also yes config it already generated a file called PS thumpy Salvatore JSON
which inside its own style and also the configuration what is same as the
client-side application like it will replace your in one minor PS with
whatever you have a daily environment of production is pending on these as
production now let’s check what is inside your client-side application so
you use your app client-side application so as an output part it is saying like
you can generate your client side will come application inside this directory
inside is a but I want to be a mass browser you can give me the name
anything we want let’s save the pin now go inside source
directory I can see it’s added a new file called TS config saga torjussen it
generally extend your existing is can be after Jason and also in some finer
option which added an entry module of after salwar module which is nearly get
added inside your app very free so this module is same duties as an MP 44 and in
the compiler option also it is updated your main Salvatore PS I’m sorry this
has been created nearly main server dot d s you have already mentor PS and
remember PS what is the update the hat it’s actually craft neo bootstrap model
bootstrap inside this addeventlistener and whenever your dumb cunt it is loaded
between either you’re at 9 side bootstrap it also create this app server
body with OTS so what we have seen and it will bootstrap your app component fix
certain area angry model all that Israel is being forecast reinforced on already
there it also imports are one module from the platform Bowser there’s pretty much bullshit and then
what still you need so fast let’s install you’ve the required modules
which has not been installed by angular concerned so one of them are expressive
engine because in the server in with the use Express engine take your factory
file which is like already compiled and then send that as a string to your
client side and also your client side application bin bootstrap and use that
particular wind solver in that file so let install your bodies and the reversal on bond stress origin I’m as iam in your replication we’re
going to use lazy loading models so if yes then also you need another
model to be installed called model map energy factories order so let’s install
that as so now our application is almost ready
but what additional thing is record is a server which actually do all these
things on the server-side rendering currently our application is already
capable of rendering the server module as well as the client model because we
already did the configuration in the angular Jason so now we need a server as
well as whatever the build produce is nothing but a factory which also need to
be compiled as a J’s which the server dot RTS 5 which is for solver will
create that also need to compile as a J’s for that in it and wave break file
as well so let’s create that all of this tutorial
files is available in my github repository we’ll add the section you can
actually download from the video itself in the link and then some bubbly
so let’s now just first create that file you can simply copy that from my repo
the first file called infect server config dot PS let’s just I’ll go to one by one here I’m saying we
need the pop module also wave back and then what you are saying the entry point
will be Salvador Pierce it will be going to be it right now and then we are
saying the target B is node and it’s odd resolved the TSN J’s fight for optimizer
we are saying don’t many ways our fight and the output will be inside this
folder and the file name will be the same as whatever the innkeeper name is
and in the module block we are defining like for PS file
heustis loader as a loader and also you can see the plug-in section we have
defined some thing which actually mitigate the issue like whenever you run
this project the Salwa dot J’s will include all the dependency from node
module itself so inside somewhere when you deploy there is no need to do any
implement store because your server torches is a complete file which will
hold all the required dependencies on it so some time it’s providing some of the
critical warnings and this block is for that now let’s create the server dot ES
file for the time sake I will again copy it
from my repository so what we have added here so we have
imported view of the body like we already installed in G Express engine
which we have reporting here so for now it’s comment out this part I will show
you what is the difference or what is the purpose of using that now we have
both installing Express also this solve our energy model which will be created
upon building your server server project we are making this as a dependency okay
also importantly of the required bodies also began importing provider model map
as I said if you are using lazy loading then this is required now we are saying
the port our application of the server we’re going to use as take it from
process dot environment if it is not available you can it will fall back to
the default or the this hard-coded value this part of the code basically provides
the support of window in your map division because as you know in the
server there is nothing called window so in few cases where you used we know in
the client side you are giving some object or you are storing something so
for that if you use window then you might get lots of error in your server
logs like window is undefined to mitigate that you can use the card
now we are not actually setting the Xmas and then what we are using and the
Express engine to bootstrap our server module ng factory which will be getting
generated you read the application also this is
very important part if we want some value or the some additional values you
need to pass to you the application this is very you can think about a
server-side services I can give you an example if your application have some
server-side the critter properties or some environment variable from that
environment variable you can pull up those values using process torjussen
process dot environment or particular key and then pass that value to your
application using this provider in future lecture I will try to provide
some very good example of this for now just understand you can use this to pass
any information theoretic next thing we are defining the Scotty how our server
will know where our static asset is there also I have added some expiry for
better castle now here we are saying whatever the request comes in to your
server then as a response just provide the index dot HTML but it is really it
is actually not fatal solution because what we are saying whatever the round or
request comes in with our application always send to index a stable but in
case you have other rule gives it a project for an example we have created
device detection wherein there is a route called device which will return
your device detection like is mobile browser or whatever things that will not
work if you heat like your application / device type it will
take you to index dot HTML which is not corrected so return a JSON so if you use
this one character start that means any request will take you to it does not
explain the better solution would be if you have routes in your project you can
create a new file called route cocktails and that ranks basically you can input
inside this project and then look through snout and pause that routes
information here so what we are saying in that case like whatever routes only
for those route radar candid stoppage-time
in the curator lecture I will also going to provide that particular information
how to do that now this is basically the complete support dot b is 5 now let’s
next important thing is in package transition when we generate the project
it have few basic scripts but could enter your application we need some
additional script or additional steps so again I will you go to my report oh no
can look back in the tips I have already added few of the command I will go
through one by one for that engine so first what we are saying here so if
you see these things link client and server bundles here we are seeing ng
build so ng buildings you know to build your client-side application and we
thought we are saying build these as a production level so it will minimize
create Factory and all these things and also once that is done with this end and
next we are saying to run demo server production for we need to change this
demo to a session because our application
it’s a scissor so you need to replace it well what about the project then you
have added so if you go to insist then Salman production if you see this
angular division what we are seeing here it will do a scissor then sulfur-sulfur production this is this will bend your
client side as well as saga side both have both a political and create app
server model engine factory poly inside the disk folder or its name hidden
folder actually now what we are saying the next step is this way that’s our
thing so what will be so it is actually here calling with that and as on
configuration we are passing these in fact config server config dirty air it
will take your sub or dot CPS and create a server dot J’s file inside your dist
for now if we add these two things and create a new spit so what it will do
when p.m. run big client-side server and also that means it will run these four
things and once that is build a complete they we can actually create another one
to run our application to run our application as a leasing node
application what we can do node inside this there is a server the J’s which
will be automatically generated we can figure that it will run your son one on
port 8000 and again to make it more simple we can plop together these two
script and create a single one on what we are saying in VM run build a scissor
and once it’s done then run the sulwon again so now let’s try to start that
let’s see what out even the things so now it’s asking like whipped egg must
be installed do you want to install the pegs here like just pass this this is
for one time next time I don’t think it will ask again or you can install we
Peck CLI globally by running NPM install went back to CLI energy yes there are few issues we need to
resolve before running this activity let’s see what is that so first thing it’s saying it’s not a
it’s trying to find J’s file wherever we have created TS v my dad so let’s change
it to this let’s start the application again another nothing well on the loader we have a radius
loader but we already installed so let’s install that and then the spawn yes Noah
and this time I will make these as a cave dependency so cryptic let’s start back to the elevator so inside
Domino’s we have used not page which has not been installed we need to install
that let’s try to start it again hope this
time there should not be any issue yes without anything all I get is about
this pocket that you can see the page is rendered through some work by just we it
so so we can see the only thing feeding inside found after Lanka in family level
so you can see this at route all the things inside of you you all say
relevant in the throat 3 but if it’s inclined side that we become II could
only see is aptly fat and inside there this is nothing like differently are
that’s a beautiful wedding when you inspect any man you can see like it’s
been injected but in actual when Google or other color will try to crawl
actually it’s not there because it’s in runtime it’s injected into your Dom but
in several entered application whatever is rendered from the server the whole
fragment or the HTML is available as a few shows like the other servers are in
applications like PHP eg a speed on this thing so you can see it’s correct
Avenger now the next thing one additional point of improvement we come
nation here in that new clothes like that location is already fast very fast
like in the client-side application you can see the delay but if like a
server-side application it’s pretty fast customers you can see already is coming
very fast become visible of – and see expected on the values – so you see what
all the Chan or Genji’s file it’s loading three points
one point on the field name and also a CSS file which is 24 bytes and the J’s
files of the maximum file size yeah please 262 kV or make dodges
and you know whenever you do any vision ugly bitter during the development it
will slowly grow your main dot JS file right now we’re is very minimal coding
side still is 262 Kui we can do two things to make it very
compact or you can actually compress this file size so that our application
will load much faster than it’s significant for this remember eyes have
previously commented out one section in Salvatore PS file that is this
compression this is another model available which will enable your
application on inside the Sun were to make it this is it
so we can generally reveal all your JS CSS which is rotate through you have
typical so let’s encode that and then also in
apple juice MIDI here when you clean stone that so it will install stop that be given again for those of us started let’s go to that
page again well load is again where you can see the
main begins file size now become 71 came only it’s almost half or more than that
reduction in file size when Indianapolis compression under not saga it is very
useful in this case of a application which is very large enterprise the
replication we should enable gzip completion of list of broccoli list
formation and that’s pretty much it for today
I hope you like my tutorial and if you did then please don’t forget to Like and
subscribe and also don’t forget to ring the bell so whenever I upload a new
video you leave notified thanks a lot for
watching thank you

27 Comments

  • Manoj Isaac

    Sir good effort
    Please add the following
    1. How to use the rendermodulefactory as shown in angular.io
    2. How to run the hybrid approach of static pre rendering and dynamic ssr together as shown in one of the YouTube videos?
    Thanks a lot

  • Praveen Kumar Guda

    Good efforts, But I think you should have explained more in detail and show the folders created inside the dist after running the project and explain the those folders.

  • BlackBox Tech

    Please stay tuned for all upcoming videos. I generally publish videos every week. You can also watch my other playlists

  • Squapl Magazine

    video position 22.30 (routes) you have mentioned will cover in another lecture. have you covered it. will be of help if we can understand that concept.

  • Sachin Bahegavankar

    Hello Sir I get error form server.js file

    var DragEvent = ((window)).DragEvent; ^ ReferenceError: window is not defined

  • Saurabh Ghosh

    Can you please tell me the routing part of the Universal because I added routing in my app but the source code of the app isn't showing the dynamic content.

  • BlackBox Tech

    Hi all, please use this link for updated code with lazy loading and ssr route
    https://github.com/kalyan11021980/angular-universal-cdnconfig

  • Sachin Bahegavankar

    Hello Sir, Actually I am new in Angular, I am trying to convert my existing app to Angular Universal my repo is https://github.com/Sachin124/angular-_universal

  • Esteban Vera

    hi friend excellent video, some questions:
    1. how can I render modules lazy loading.
    2. How can I render information from the server using an example service: https://jsonplaceholder.typicode.com/posts
    3. How can the project be published on servers such as herokuapp or firebase

    This is my example project where the lazy loading does not work for me
    https://github.com/luisestebanvera/angular-universal

    stay tuned,
    first of all, Thanks!

  • Vaishali Kasar

    Hi sir, getting error Cannot read property 'projectType' of undefined error on ng generate universal –clientProject command.

  • Vaishali Kasar

    Hi sir, getting Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js) on npm run build:ssr && npm run serve:ssr command

  • Indraraj yadav

    Hi, when I hit http://localhost:4000, it start loading indefinitely, but when I hit http://localhost:4000/index.html it loads full page immediately

  • Shalini Singh

    Hii I got two error after follow all your explaination
    Module not found:error: can't resolve 'filter-env'
    Module not found:error: can't resolve '. Dist/server/main'

  • Sabry Muhamad

    that was very supportive but unfortunately I got the same error I always get with angular 6 using universal toolkit… the error is::
    ~tevadistserver.js:145902

    })(window, document, 'Hammer');

    ^

    ReferenceError: window is not defined
    at Object.<anonymous> (~tevadistserver.js:145902:4)

    at _webpack_require_ (~tevadistserver.js:20:30)

    do you have any idea what I should do please?

    p.s. here is a compress version of my project
    https://github.com/sabrymuhamad/teva.git

  • Sungira Info

    Hello brother, thanks for this video and God bless you,.. Please i am getting this error after running npm run start-ssr ERROR in ./server.ts

    Module not found: Error: Can't resolve 'dotenv' in 'C:wamp64wwwnaipod3'

    @ ./server.ts 13:13-30

    ERROR in ./server.ts

    Module not found: Error: Can't resolve 'filter-env' in 'C:wamp64wwwnaipod3'

    @ ./server.ts 10:16-37

  • Vijay kumar

    Hi, thanks for the video.
    After node dist/server.js
    i'm getting
    var crypto = require('crypto');
    ^
    TypeError: require is not a function
    Can you please help me to solve this.

  • Mujamil Naikwadi

    TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Storage.initialize (/Users/Desktop/Project/buyer-app-universal/dist/server.js:288587:45)
    at new Storage (/Users/Desktop/Project/buyer-app-universal/dist/server.js:288478:14)
    at StorageService.initializeForBrowser (/Users/Desktop/Project/buyer-app-universal/dist/server.js:288669:22)
    at new StorageService (/Users/Desktop/Project/buyer-app-universal/dist/server.js:288656:18)
    at _createClass (/Users/Desktop/Project/buyer-app-universal/dist/server.js:21722:20)
    at _createProviderInstance (/Users/Desktop/Project/buyer-app-universal/dist/server.js:21696:26)
    at resolveNgModuleDep (/Users/Desktop/Project/buyer-app-universal/dist/server.js:21660:21)
    at NgModuleRef_.get (/Users/Desktop/Project/buyer-app-universal/dist/server.js:22368:16)
    at Module.inject (/Users/Desktop/Project/buyer-app-universal/dist/server.js:5072:33)

  • Vijay kumar

    This helped me a lot. thanks for the video. But I got stuck in dynamic content. If my app is making api calls and rendering data, this part is not getting rendered in server side. Can you please help me out in this.

  • Vivek C

    Issues that I faced other than the ones shown in the video:
    1. Added new routes.ts file in src folder to resolve an issue in server.ts
    2. Can't resolve 'dotenv' and 'filter-env' – Installed both and the issue is resolved
    3. Can't find module 'postbuild.js' – Copied the required folders & files from the given repo link
    Now my ssr on a new angular project is successful. Need to do the same in an existing, larger project.

  • Vivek C

    I implemented the same in my existing project and the ssr was successful as it's showing "We are serving the site for you at http://localhost:8000!". But as soon as I open the url in browser, the console is showing this error "ERROR { Error: Uncaught (in promise): ReferenceError: System is not defined ReferenceError: System is not defined" and the url doesn't load. I'm not using systemjs anywhere in the app. Please help.

Leave a Reply

Your email address will not be published. Required fields are marked *