How do I share javascript on the server as well the client? - javascript

Lot of the time I end up repeating the code on the server as well as the client. Example I have a registration form; validations I do for required field, email address regex are same on the both server and the client. I ideally want to write code in one place and not repeat.

If you're using express.js, take a look at the express-expose module. It seems to do what you're looking for:
expose objects, functions, modules and more to client-side js

I am going to assume that you aren't talking about a node.js application (for that take a look at either now.js or express-expose).
In these cases, what I would recommend is to do as much server side as possible, as a client can disable javascript (the is a particularly strong point when dealing with validation). You could use ajax to hit up the server, run the code there, and return in javascript.

Related

Javascript: How to execute at the Server Side (back-end)?

Lets say I want to do the JS execution, like, processing Javascript Elements but on the Server rather than exposing the code(s) on the client JS file.
Something like, lets say:
From the browser's side, lets say i will get the JS native window Object.
Then i want to make all Javascript processing works (on that window Object) in the backend by passing it to backend via Ajax, or whatever. So as an very simple examples (to do on the Backend JS Server):
Parse the window.location and do some codings related to it.
Parse the window.document and do some codings related to it.
And then return back to browser with the respective outcomes and then so on ..
So that means, (based on this simple example), i want to perform the parsing and whatever coding works, related to window.location & window.document Objects, in the backend (another) server. Just by passing this window Object to it. (Then return the already processed result back to the browser) So the user wont see what i am doing with this window object.
** Above is just a simple example. In fact, i want to pass some more complicated JS Objects and process at the backend.
That obvious point here is, i do not want my main JS processing codes to be exposed to the users.
Is this "concept" even possible please?
(If possible, what is the ideal approach to this?) Especially for the BACKEND, what should i be running and HOW, please?
Thanks
No, this is not possible as you describe.
JavaScript can run on the server, if your server has an engine to run the scripts. Node.js, which you tagged, is a good example of that.
But still, server and client are separated. The server cannot directly modify elements that are loaded into the client. The server feeds pages or other pieces of information to the client, which can be processed by the client.
So you could make an AJAX request to the server to perform some logic. This logic can be executed by PHP as well as Node.js, but when it comes to modifying the DOM, there is not much difference.
Node.js can be helpful, though. It supports a DOM as well, and I think you can even use jQuery, so an advantage over PHP is that you can do DOM manipulation in a similar way as on the client. It saves you a language to learn, but the client/server processing is still separated. You can't send an element with all its data and attached events to the server. You can send serialized objects at most.
Javascript is a client-side programming language and all code is interpreted at runtime by the browser on the client's machine. So the short answer is no.
For server-side code, use a server-side programming language such as PHP, ASP.NET or ColdFusion.

How effectively can I use angularjs keeping security in mind?

Why should I use angular.js or other like js frameworks when I know they are not secured.
What I mean by security is:
All the code is written in pure javascript. The javascript can be edited in devtools or firebug. Something like form submission can be easily manipulated. Even if I try to do server side validations for all the http requests, I end up doing double the work.
How can I effectively use angularjs keeping above in mind?
Thanks.
All client side code is susceptible to modification. For that reason you don't put anything that needs to be secure into the client code. The client code should define the view elements for the end user and give them an easy means to communicate with the server. Regarding security 99% of this needs to be handled server side by appropriately protecting the data that is sensitive. In terms of server to client communication you need to use SSL. Angular has some things built in to help with security see $sce and ngSanitize but IMHO your back-end should be safe because anyone can re-write a front end or use a command line tool to send various curl requests at the server until something gives. The client code really has no need to contain anything proprietary outside of the client code itself if that's your concern you can use obfuscation tools but ultimately even compiled code can be decompiled or disassembled .
You should always do both client and server-side validation. No matter what library you're using, this is required. It shouldn't be seen as "double" the work. It's just "the work".
Even if you weren't using Angular (or another Javascript library), I could still use devtools to make a request via Javascript to your server - it still needs to handle it.
If you're worried about code security, you can use an obfuscation/minification tool.
Of course you should use minification js tool for your client side code if you worried about its logic. But keep in ming this:
Do not keep service info (like many id`s and etc.) on client
And always use both type of validation in dangerous places
Use crypto/tokens

Ruby in web browser

I'm looking for some solution of next problem: Now i'm developing an Rails app. I want to have possibility to code in Ruby at browser and then execute that code in my Rails app.
Are there some ready solutions?
UPD:
what about code highlighting?
what about Native Client?
https://github.com/codegram/rack-webconsole
Or you could simply pass the Ruby code to the server via post and call eval eval(CODE).
You should note that especially the second way is very insecure since it gives the executing code complete access to your system.
If this really has to be done "Locking Ruby in the Safe" could help secure it.
EDIT:
For syntax highlighting take a look at Code Mirror and ACE. Both are decent source code editors with ruby support.
There aren't really any real-world deployable solutions for this yet, but you might look at text/x-ruby as a proof of concept.
There's also the Cloud9 IDE which functions as a browser-based IDE, and will persist code back to your server to be run.
eval is what you are looking for. A user enters Ruby-code, which gets POSTed to your rails app. Inside your controller you will need to eval the submitted Ruby code.
But. You probably don't want this. If there really seems to be a need to evaluate and run user submitted code, you most probably will need to re-think the need for that feature. This is almost impossible to make secure. And even when you secure it from certain users, it can be exploited trough XSS; which can actually take over a server in no-time trough this "feature".

Is JavaScript validation bad?

It has been long time since we have been validating our forms using JavaScript. I am sure this must be the case with most other developers.
Question:
What if the user (or probably a bad guy) disables JavaScript?
You are lost!
Is JavaScript validation worth of it?
Should we ever use it now?
Are there any solutions to this?
Correct me if I am wrong.
Is JavaScript validation worth of it?
Yes, as it provides a better user experience and preserves bandwidth.
Should we ever use it now?
Yes, for the aforementioned reasons.
Are there any solutions to this?
Yes, use server-side validation as well.
What if the user (or probably a bad guy) disables javascript?
As said before: Simply do not rely on the client. Never do so. Check everything on the server again.
Should we ever use it now?
Yes - so the user immediately sees what's wrong. Otherwise he had to post back the data first which may take a while. By the way you reduce traffic to your server.
It's simply more inuitive.
//EDIT:
BTW: The ASP.NET ValidationRules contain both client-side and server validation as far as I know.
Javascript validation is good because it provides a better user experience.
You should however never rely on it and should validate on the server regardless.
If you're looking to save time, go with server-side only. If you want better performance and user experience, add client-side validation afterward. Never rely on client-side validation, for the reasons you state. All critical validation should occur on the server ... even if duplicated on the client.
JavaScript improves user interaction for your product or service. Users interaction (user input and machine response or vice versa) is a vital characteristic of our applications. As we all experienced, products are getting more interactive ever than before. And this interaction part can (only) be crafted in JavaScript (ActionScript for Flash Player). We would all agree with this - there is always a calculated amount of work that can be transited to the client side (machine) to avoid calls without bothering them to send to the server(s). There are many many applications which are heavily dependent on client-script scripting. And if they found you do not allow required scripting they asked for it leaving a message in noscript tag. But I think everyone wants to have it enabled as we all fire up a tab with Gmail, Facebook, etc.
However, this still should not be ignored as we are keen to grap every single opportunity (audience/customer) and work with is at least better than falling apart. It still works!
As a Microsoft Development Platform user, there is a convenient solution on .NET platform. That don't require dual effort on such issues. Make use of your client-side validation while scripting is disabled by using Page.Validate() and Page.IsValid.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) {
Page.Validate(); // If you missed, then you got the second chance ...
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid) { // Confirm you do a proper validation before moving to perform any process
Response.Write("Done!");
}
}
I hope this will help.
Client-side (Javascript) validation is about usability, nothing else. If the cost of implementing is not worth the perceived increase in usability, then don't spend the time on it. These days it's pretty easy to do though!
I don't think you can do without server-side validation, however, since this is the only thing that provides you with any security.
Using JavaScript is not wrong. We've been using it since a long time. It is used for applying client-side validations.
Still, we should implement server-side validation so that a bad guy would not be able to break the application.
If you learn only one thing from this topic, let it be this:
Never — under any circumstances — trust data from the browser and always validate request data on the server-side.
Should we ever use it now?
Yes, definitely. You do not need to validate an empty field on the server side. It is not something like validating an email's availability (uniqueness of email). If you are going to reject that empty field anyway, there is no point of sending it to server and making
server do extra work for it.
You have to validate it on sever-side, javascript is good to validate form, but people can disable javascript, or use another javascript to hack it, so validation on server-side is a must.
JavaScript is useful for client side validation. But you cannot rely only on them. You must use server-side validation against the posted data. JavaScript just prevents unnecessary posts to the server.
You can make server and client-side validation pretty painless by using a framework that supports both. In the past, for ASP.NET I used the Peter Blum validators:
http://peterblum.com/
With this, you drop the validation controls onto your page, hook them up to the inputs (textboxes, drop down lists etc), and specify the validation properties (minimum length, required, error message etc). When the page runs, the framework spits out equivalent code for both the client (JavaScript) and server (ASP.NET) to perform your validation.
Without such a framework, as other posters have pointed out, validation can be laborious.
I'd be interested to know of anything similar for PHP or other technologies.
You should have multiple layers of validation.
Validation on the client Side
This is definitely useful because validation can be done without having to go to the server. Requests get to the server once they are validated - saves some traffic.
Validation on the server side
If javascript is disabled then the server should also incorporate a level of protection - validation in order to disallow erroneous requests.
In a multi-tiered / service orientated environment validation should exist on multiple levels to allow for better reuse while still maintaining a secure application. Validation on the client side, whether in a desktop app, or web site/application should be there for a better user experience to prevent postbacks to the server everytime for validation, hence costing more bandwidth and user time. If client-side validation cannot be moved entirely to the front end then consider using ajax for a partial postback to a server side validation routine, while retaining a better customer experience but allowing a programmer to maintain the validation rules centrally.
Second to the client side, but more importantly, server side code should validate the data before persisting it via a data layer or passing it to another server side method/service, to employ business rules around the data and help prevent errors in data integrity. Lastly, the persistence layer itself (the immediate interface to the database or other storage mechanism) should validate the data being stored, again to prevent errors in data integrity and possibly further business rules. The last thing you want is a data store with useless data.
Employing this method will keep you data secure and integrity in line. On reuse of either you persistence layer, your data layer or your front-end presentation thereafter, in your own site (or via a web service, desktop application or mobile app), if designed properly, these validation routines are already in place and can be re-employed. This should prove to be of great benefit to you alone, and your colleagues and your management, if you happen work in a team.
Is JavaScript validation worth of it?
well,yes it is .Buy using JavaScript validation you can easily take any kind information about client site more over JavaScript validation provides a better user experience
Should we ever use it now?
Yes you can because of user can see there error or what's they do wrong on real-time
Are there any solutions to this?
yes you can also use server-side validation.But sometime its take more time .it's also insecure
Javascript is a client-side scripting language. Therefore we can use client-side validations by using it. It helps to reduce the load that goes to the server-side. That's why js validation is worthy. And that is the reason for use it for client-side validations. But we should not only depend on js validations. Because the client can turn off the js engine at any time. If so, it causes a big problem.

How do you synchronize server-side and client-side code?

Something I've been learning (and teaching) in Software Engineering is that code duplication is the root of all evil. On the other hand, I find it quite hard to explain how this concept should be applied to the development of web apps.
Allow me to clarify... Input & data validation can be an important part of a web app. Sometimes this validation can be quite complex. For example, I worked on a puzzle editor and the validation consisted of checking whether an operation or a move was valid. Non-trivial rules then had to be checked.
Naturally, validation must be done server-side in order to ensure the consistency and quality of the stored data. However, it's a must to do validation client-side to ensure a smooth user experience.
In most instances, client-side and server-side code are written in different languages (i.e. javascript/Python), so validation code has to be written twice. However, in my only experience with GWT/Java (Java on both sides), I found that a large portion of the validation code could be reused. This seemed to make everything easier: maintenance, refactoring, debugging...
So my question to you is: how do you manage issues related to code duplication in projects where the client-side and server-side languages are different?
The way I usually handle this is to write the validation code on the server side and expose it via a web method (in .NET, similar functionality exists in most other languages) so that it can be called from javascript. As a result, you have a single method that can be called both synchronously and asynchronously from the client side and also called from the server side. This isn't applicable in every case but it's worked very well for me so far.
Typically, it's really hard to avoid duplicating the generated code, but a common approach is to use a code generator to build either the server or client side code so you only code one half of it. The most popular approach is writing the server-side common and then having the code generator build the JavaScript code for you. For instance, the language we use at my company is Coldfusion and Form-o-matic solves that problem for us. People have also approach the problem from the opposite direction by writing JavaScript which can be executed server side. I'd look for a framework that will do this for you.
A possible solution is that you abstract the actual validation in a validation description file (in XML or any other means) using a DSL. This way you only need to implement the validation engine in both client and server language and base the validations on the same description file.

Categories

Resources