How to forward non-www to www domain name and vice-versa#

Forwarding domain names according to the requirements of 'www' is trivial in Apache using .htaccess. It's not hard either in Node.js, if you are using Express.

Put the route definition of your requirement on top of all other routes in Express.

Forward www to non-www domain name#

This will detect the presence of 'www' and redirect the request to the domain name without 'www'. The status code of 301 means that it is a permanent redirect. If you omit the status code it does a 302 (temporary redirect). For SEO purposes it is best to use a 301 redirect.

app.use(function(req, res, next) {
  if (req.headers.host.match(/^www/)) res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url, 301);
  else next();
});

Forward non-www to www domain name#

This route detects the absence of 'www' and redirects the request to the domain name with 'www'.

app.use(function(req, res, next) {
  if (!req.headers.host.match(/^www/)) res.redirect('http://www.' + req.headers.host + req.url, 301);
  else next();
});

As simple as that!