Render Backbone.js application on the server AND the client - node.js

Supposed I have a web application that is built using Backbone.js and Handlebars. As server I am using Node.js. Now I want to do rendering on both ends, i.e. on the server and the client.
When a route is requested for the first time, the server shall do the rendering (mainly due to performance reasons). After that, all following actions shall result in client-side rendering.
This means that I must be able to render any page on the client and on the server, both times in the perfectly same way. Both ends have to support the same kind of routes.
How could I accomplish this task?
At the moment, I have taken a look at AirBnb's rendr project, but this definitely ties me to Backbone.js (I'm not sure if I want to stick with Backbone.js for all times), and seems to be not perfectly finished yet. At least, AirBnb does not recommend it for production use yet.
Any other ideas on how to do this?
As a sub-question I might also ask: What is the preferred way to share JavaScript code between the server and the client? For this, I also know piler, but I could imagine that there may be better solutions available.
Any hints?

Well, I am building an application that does this. If you don't want to use rendr, you will have to code your own versions of some of the things they take care of. AFAIK at the moment your choices are rendr or home-grown. Here's some misc tips.
We use cheerio for server-side DOM operations, so when views render on the server, this.$el is a cheerio element instance. In the browser, it's jQuery.
You don't need event delegation and binding on the server side. Our code technically does this at the moment, but it's pointless and a cleaner solution would avoid it on the server
Once you have server-rendered HTML in the browser, you need a way to wire up a big nested tree of view instances to their corresponding elements in the big nested DOM tree. We have a home-grown solution for this, but Backbone.View.setElement is the core and you'll need to write some code to make this happen
We are re-rendering on the browser at the moment although there's probably a slicker way to take a view instance, give it some options in the constructor including a pre-rendered DOM node, and get things properly wired up without re-rendering. That's an exercise for the reader though. :-)
We also send down the raw data we need as JSON within a <script> tag so we have both server-rendered HTML (for perceived performance) and the raw data available as JSON so we can get our backbone models and views instantiated and operational. Again, you'll have to come up with some code to manage this situation.
We use browserify to bundle and share code between server and browser. All of our JavaScript is coded as CommonJS modules.
We have a basic isBrowser() function in our view parent class so we know when browser-only code should run for event bindings, etc.
Anyway, for what it's worth, after working this way for many months, I don't think backbone works well with this paradigm. Many of the core concepts from backbone are fine, but it doesn't lend itself to mapping view instances to pre-rendered DOM nodes. Bootstrapping models and collections from JSON is easier, but the view layer probably needs a significant fork to operate cleanly in this style.

Related

Making website with Node.js without framework

i want to create a website based on node js and mysql , but i've read that there is a framework called express for node js , and i'm wondering if i must to use such kind of a framework to create a decent website or it is possible without it and just work with pure node js.
No framework is required. You can write a full-blown web server using only the http module or if you really want to write everything yourself, you can even do it with only the net module.
It's really about what is the most effective use of your time and skill as a developer. Except for academic or pure learning experience reasons, if you're just trying to accomplish a task as efficiently as possible and free, pre-existing, pre-tested code exists that makes your job easier, then that's a better way to go.
For example, if I need to do a file upload from a browser to my back-end and the data is coming in as the multipart/formdata content-type from the browser, I have zero interest in reading and learning the multipart/formdata RFC then writing my own code to parse the multipart/formdata content-type. Pre-existing, already tested code exists to do that for me and I'm adding no value to the goals of my project by re-implementing and then testing it all myself. Therefore, I'd like to use a pre-built module that does all that for me. I can just configure the right library on the right route and out plops my uploaded file in only the amount of time it takes to understand the interface to the 3rd party module and how to use it properly.
This is where Express comes in. Not only does it offer a useful set of features and architecture for configuring routes, installing middleware, sending responses, using template engines, handling errors, etc... but there are also thousands of third party modules that are built to hook into Express and it is easiest to use them if you're using Express as your core framework. Some of these modules could be used outside of Express, some cannot - it really depends upon how they're designed and what Express interfaces they do or don't use.
Also, Express is fairly "un-opinionated" and fairly "lightweight" which means it doesn't force you into a particular methodology. It just offers you easier ways to do things you were already going to have to write code for yourself.
Look at it this way. When you get node.js, there are thousands of APIs that offer lots of already tested things such as a TCP library, a file I/O library, etc... Those are frameworks (in a sense) too. You don't have to use them either. You could rewrite whatever functionality you need from scratch. But, you wouldn't even think about doing that because tested code already exists that solves your problem. So, you happily build on top of things that are already done.
One of the BIG advantages of coding with node.js is getting access to the tens of thousands of pre-built modules on NPM that already solve problems that many people have. Coding in node.js with a mindset that you will never use any outside modules from NPM is throwing away one of the biggest advantages of coding with node.js.
could you tell me what are the Routes used for in frameworks?
A route is a URL that you wish for your web server to respond to. So, if you want http://myserver.com/categories to be URL that your server responds to, then you create a route for /categories so that you can write code for what should happen when that URL is requested. A framework like Express allows you to create that route very simply with just a single statement such as:
app.get('/categories', function(req, res) {
// put code here to handle that request
});
This is just the tip of the iceberg for what Express supports. It allows you to use wildcards in route definitions, identify parameters in urls, create middleware that does prep work on lots of routes (such as check if the user is logged in), etc...
You don't have to use a framework but it is recommended to use one of them since frameworks like Express make your life easier in many ways. Check this: What is Express.js?
Yes you CAN write a Node.js-based backend without any back end implementation framework such as Express. And if you are using Node.js for the first time without any previous experience of asynchronous coding, I'd advise against using Express, KOA or other Node implementation frameworks for your simple learner apps (e.g. those needing things like register/login form processing, logout button, user preference updates to database, etc) because:
(1) Node.js is a core skill for JavaScript back ends.
Stupid analogies between server tasking and restaurant waiters are no use to a real web engineer. You must first know what exactly Node can/cannot do in the server CPU that makes it different to most other back end technologies. Then you have to see how the Node process actually does this. Using Express/KOA/Hapi/etc you are sometimes effectively removing the mental challenges that come with a Node back end. Any time-saving is achieved at the expense of gaining a proper working understanding of what Node is and how it really operates.
(2) Learning Node.js and its asynchronous coding is hard enough without the added complication of coding with an unknown framework like Express/KOA that assumes users' familiarity with JavaScript constructs like callback functions and Promises. It's always better to learn something in isolation so you get the essence of its individual effects, rather than the overall effects if used with other packages/frameworks. So many of these Node.js Express tutorials are the software equivalent of learning to make a cake by watching Momma do it. We can copy it but we don't know how or why it's working. Professional coders can't just be good copycats.
(3) Available learning tutorials using Express often drag in other technologies like MongoDB, Mongoose, Mustache, Handlebars, etc that make learning Node.js even more awkward still.
(4) A share of basic web apps can be written more efficiently with Node.js, custom JS and existing JS modules imported off the npm repository rather than with Express.
(5) Once asynchronous coding and the JavaScript constructs available to assist with it are understood clearly, pure Node.js apps for basic tasks aren't that hard.
(5) After you do get your head around Node.js and can get basic web app functionalities working using server-side JavaScript constructs, you can then judiciously start to explore Express/Hapi/KOA/etc and see what an implementation framework can do for your workflow when doing larger projects needing numerous functionalities. At this point you know what Express code should be doing and why it is done the way it is.
Node.js has become the back-end technology of choice for most small to medium scale web applications over the last 10 years. It is also the major reason why the JavaScript language has evolved from a mere front-end scripting tool with a limited set of Java-aping constructs to the innovative and comprehensive language that it is today. It is also the most popular language in use today. Investing time in understanding the Node server framework, and the latest JavaScript constructs used in Node, is time well spent. Implementation frameworks such as Express, KOA, Hapi, Sails, etc have great benefit when writing more elaborate back ends on the Node.js platform. But all these implementation frameworks are predicated on the behaviour patterns of Node.js. So unless Node itself is understood first, the full utility of Express/KOA/Sails/etc will never be enjoyed.
Try here for the pure Node.js.

Express route handler like functionality in Sails applications

TL;DR Is there a way to have Sails applications work similar to Express route handlers?
I'm working on an application that has a few major components (e.g. ecommerce, blogging and so on). It's working all fine, but the huge number of models, controllers and views is making it difficult for me to visualize them as separate components and making me feel a little too congested for comfort.
I've been through threads like this and I understand nesting is available for controllers, but I really want to split my project into discrete components.
What I'm doing now is splitting the project into different applications and exposing their REST APIs for the gluing application to show its magic. At least this would do the much-needed segregation. But how do I make the endpoints accessible to the gluing application? Using req? While that would give me the liberty to host the other components on another machine, it would slow things down considerably, right? Is there a way to interact with the other processes "directly", something like route handlers in Express (though they're not separate processes)? I would ideally like to have them running as separate processes so one component doesn't bring everything down on failure. At the same time, I want the interaction to be as "local" as possible.
Am I missing something fundamental here? Any suggestions would be appreciated.
Also, is this more of a serverfault question?

Handlebars JS Precompiled Faster Than Just Rendering On The Server?

I apologize in advance for the total noob question about Handlebars. I'm coming from a Rails background and while Handlebars looks cool I'm having trouble seeing it's advantage over compiling views on the server.
So here are the questions.
Currently, our apps compile Handlebars JS templates on our node server, and pass fully rendered pages back to the client. I've been asked to look into precompiling the templates for render on the client.
First, I'm a bit perplexed by how to architect this. Would the initial download to the client just be like a layout template (just boilerplate html, css, and js), then the client would use whatever json data gets passed to it, along with the precompiled templates sitting in Handlebars.templates to build out the details of the views?
If so, is it really more efficient to load up the client with every possible template it may need, rather then just serve up only what it needs at the time it needs it?
First, I'm a bit perplexed by how to architect this. Would the initial download to the client just be like a layout template (just boilerplate html, css, and js), then the client would use whatever json data gets passed to it, along with the precompiled templates sitting in Handlebars.templates to build out the details of the views?
If you are doing things robustly, then you would serve up the server rendered page as usual.
That would include a <script> which had the templates embedded in it. They only come in to play at the point when a second page would normally be loaded from the server.
If so, is it really more efficient to load up the client with every possible template it may need, rather then just serve up only what it needs at the time it needs it?
You have an extra cost on initial load. If your data is appropriate then this pays off in the long run as you don't need to refetch entire HTML documents every time a new page based off the same template is visited (and in some cases, where all the changes can be calculated client side, you can avoid some HTTP requests entirely).
It is not faster for initial load.
But if you're doing a "single-page" application, then every changes after the initial load will be way faster. It'll give a more dynamic and fast feeling.
But if you do rails with forms and if you're not doing a "single-page" like app, then there's no reason to render client side.
This really depends on the particular needs and limitations of your application. The advantage of templates on the client is reduced http requests and snappier performance. The disadvantage is increased bloat. So depending on where your performance bottlenecks are located, it may be better or worse for you to increase http requests compared to adding bloat to the initial payload. Of course, you could lazy load a package of the templates, etc. etc. etc.
As for architecting it, yes, your templates are waiting client-side. When you request JSON from the server, you plug the data into the templates and render on the page.

Why do we use server-side templating engines for Node?

For example I see Node.js a lot of peopple have been mentioning using jade or swig. I am building a Node.js app that will use RESTful interface for communicating with the client. I want to be able to send and receive updates. A lot of tutorials I've been seeing or apps I have been seeing online use jade or some other template engine.
What is the advantage of using a templating engine on the server vs. just serving up a bunch of regular html/javascript and allowing the client to render certain pages based on what information is sent to it from the server? How does a server-side tmeplating engine improve a use of a RESTful interface? edit: is there any advantage or is it just personal preference?
If it is advantageous in some way, I will invest the time to learn it now before I get too far in my project rather than wish I had learned it earlier :-D
Here is an example that uses Jade-lang.
SGML-like markup languages are hard for both computers and programmers to read. Template engines usually help speed up programming by using smaller tokens and syntax. Also, if you go through a pre-processor that templating requires, you can add variables and logic usually.
The downside is that it takes cycles to render the template. Usually though this isn't a problem, as most projects are hindered by time-to-market and not lack of processing efficiency.
I use Jade for most of my projects, because it's very easy to transition from HTML to Jade and also intuitive. I had hardly any learning curve difficulties going from HTML to Jade.
An advantage to templating engines is as they are running server side you can do permission checks directly within the template. You could even send all of the user's data inside of the template all in one request.
They have their upsides and downsides, but security is a big upside as you're not relying on the client to ignore the data its not supposed to see.
There are other ways to do this but this is for sure one of the easiest as it's all done in a single request.
I also want to note real quick that they are not replacements for other forms of permission checks, you need those too. They just help in not putting too much trust into the client.

How do I keep value objects from the server?

I communicate with the server through jsons, which both in Nodejs and in Actionscript are objects (serialized through string).
Those objects I use in my client, by reading / modifying them and also creating secondary objects (from Classes) relative to what came from the server.
I have one of two options to design my client and I am stuck at deciding which of them is more flexible/futureproof.
Keep data as it comes, create many methods to modify the objects, keep secondary objects somewhere separate.
Convert the data into instances of classes where each class has its own group of methods instead of piling the methods in the same place.
Usually I go with 2 because OOP is delicious but going with 1 seems much simpler in terms of quantity.
I guess my problem is that I can't figure out if my client is basically a View (from MVC) where the server is the Control (also from MVC), or if my client and server are two independent / separate projects that communicate, and I should consider the client as a MVC project in itself.
I would appreciate your 2 cents.
From your question it's not clear what 1. and 2. differ but looks like 1. is tightly coupled while 2. has better separation of concerns.
It depends on your application. Do you need to create client heavy app with rich UI/UX elements, or maybe a mobile app where bandwidth is limited? If the answer is yes, then go with a second approach (2.): build your MVC like structure or use existing MV* libraries, like Ember, Angular, Backbone, Knockout, etc.
If you need SEO support and don't have much of fron-end code, then rendering on the server-side is still an option. Even with this approach ORM like Mongoose can come in handy.
PS: JavaScript doesn't really have classes, because objects inherit from other objects. You can use prorotypal inheritance patterns for that.

Resources