Force www or non-www in Express/ Connect

Serving your website through either your domain prefixed by “www”, or by your domain directly (but not both) is important for SEO. For ease-of-use (i.e so as not to drive away users), it is common practice to redirect the domain you chose not to be the canonical domain to redirect to your canonical domain.

In Apache this is accomplished via your .htaccess file. No provisions exist to do this automatically in Connect or Express, but it is easy to add middleware to achieve this.

Basically, examine the host property of the request object, and call redirect on the response object to redirect to the canonical domain if necessary.

To force “www”:

var express = require('express'),
    app = express();

app.use(function (req, res, next) {
  if (req.host.indexOf("www.") !== 0) {
    res.redirect(301, req.protocol + "://www." + req.host + ":80" + req.originalUrl);
  } else {
    next();
  }
});

To force non-“www”:

var express = require('express'),
    app = express();

app.use(function (req, res, next) {
  var str = "www.";

  if (req.host.indexOf(str) === 0) {
    res.redirect(301, req.protocol + "://" + req.host.slice(str.length) + ":80" + req.originalUrl);
  } else {
    next();
  }
});

Notes:

  1. Do not forget to call next() in the event of a redirect not being needed.
  2. Ensure you are emitting a 301 (permanent redirect) rather than any other HTTP status code.
  3. Here’s an example of how I’ve used a variant of this code in practice in my own code (using the vhost module).
  4. If you’re running on port 80, you can remove the + ":80" + portion of the code within the redirect() call; if you’re running on a different port however, change “80” to be your port.

Sending FormData with jQuery.ajax()

This post explains how you can send the HTML5 FormData object as an AJAX request with jQuery. If you’re simply looking to learn how you can submit a form via AJAX using jQuery please checkout my other blog post instead; Submitting a form as an AJAX request using jQuery.


HTML5 introduces FormData to allow developers to build forms objects dynamically (and can even include files from the user’s file system), and then to send this form object via AJAX. You can easily use FormData with an XMLHttpRequest by passing the FormData instance as the parameter to xhr.send(). However, what if you want to send the FormData using jQuery?

Unfortunately, it’s not as easy as setting the data attribute to the FormData instance; jQuery runs anything that isn’t a string through jQuery.param() to serialize the objects keys into key1=a&key2=b etc; running FormData through this doesn’t end too nicely.

However one of jQuery.ajax()‘s many options is processData, which allows you to turn off this behaviour by setting it’s value to false. So, to use FormData with jQuery.ajax() it’s as simple as:

var formData = new FormData($('form')[0]); // Create an arbitrary FormData instance

jQuery.ajax('/endpoint.php', {
    processData: false,
    contentType: false,
    data: formData
});

Note we’ve also had to set contentType to false as well; unless contentType is specified as an option to jQuery.ajax(), jQuery reverts to the default of "application/x-www-form-urlencoded". By setting contentType to false we prevent this option from being set, and the browser implementation of XMLHttpRequest (which jQuery uses behind the scenes of course) will set the correct Content-Type header for us.

Be aware that no amounts of jQuery will make FormData cross browser. Whilst most browsers have supported FormData since the stone age (Chrome 7, Firefox 4.0 and Safari 5), Internet Explorer and Opera are the noticeable exceptions, with support only being added in Internet Explorer 10 and Opera 12 respectively. As there’s no real polyfill/ fallback you can employ for FormData, you should use feature detection and degrade gracefully as appropriate.

if (!("FormData" in window)) {
    // FormData is not supported; degrade gracefully/ alert the user as appropiate
}

The use of, and reasons behind, “use strict”

ECMASCRIPT 5 introduces a new mode of execution called strict mode.

As its name may suggest, when enabled it enforces stricter checks on the executable code to reduce the number of silent errors that is can easily be introduced in JavaScript. Instead of failing silently, the code will throw various types of errors; such as ReferenceError or TypeError. This has the huge benefit of allowing common programming errors to be noticed much more easily (as they throw a dirty great red line in your console), rather than failing silently and you, as a developer, having to spend hours tracking weird and wonderful bugs down to a stupid typo. Additionally, strict mode prevents usage which has been deemed as bad practise over the years; encouraging better and more eloquent code.

The beauty of enabling strict mode is that it is entirely backwards compatible and provides great flexibility to the developer where to enable it. Strict mode can be enabled either on a script level or a function level, by adding the "use strict" statement anywhere at the top of the script or function, for example;

"use strict"; // enable strict mode on a script level. 

function foo() { 

} 

var bar = 4; 

Because the statement "use strict"; by itself is perfectly valid JavaScript (i.e. it initializes a string, but does nothing with it), backwards compatibility is maintained. Your strict-mode-capable-script will still work on all the old versions of IE, albeit in standard mode.

The changes in behaviour introduced in strict mode can be perused in all it’s dry-ness in the ES5 specification, however the changes I’m most excited about are as follows;

  • Assignment of an undeclared variable will throw a ReferenceError rather than create a global variable implicitly.

    foo = 4; // TypeError is thrown
    
  • Invalid assignment of object attributes throw TypeError rather than failing silently. An assignment may be invalid due to the property being Un-[[Writable]] or the object being Un-[[Extensible]].

    var obj = Object.create(Object.prototype, {  // Create an object with an un-writable "x" attribute
        x: {
            writeable: false,
            value: "test"
        }
    });
    
    obj.x = "changed!"; // Throws a TypeError
    
  • Declaring an attribute multiple times via object literal syntax and using the same argument name more than once throws a SyntaxError.

    var obj = {
        foo: "bar",
        foo: "baz" // SyntaxError is thrown
    };
    
  • Using the bad parts of JavaScript such as with, and using caller, callee or arguments attributes throw errors (with throws a SyntaxError, the remainder throw a TypeError).

For further reading on the subject of strict mode, see the MDC article on strict mode.