Is it ok to render a mobile view in express?

1.3k views Asked by At

From a progressive enhancement standpoint, I was just thinking through different ways of enhancing a web app so that a mobile user gets a server rendered view, vs a desktop user.

One thing I was thinking about was rendering a mobile view. The basic node code would be...

router.get("/components", function(req, res) {
  var mobile = isMobile(req.headers["user-agent"]);

  res.render("components" + (mobile ? "-mobile" : "");
});

In this way, I could render a more mobile friendly view that uses less JavaScript, and render a fuller, richer SPA on the desktop.

Wondering, if, and why this may or may not be a bad idea and any alternatives you may have.

Thanks!

1

There are 1 answers

0
Pier-Luc Gendreau On

Rendering different content for the same URL based on arbitrary conditions (device, language, etc) is a big no-no.

What you could do is setup middleware that verifies whether the user comes from a mobile device and redirect accordingly.

isMobile.js

module.export = function(req, res, next) {
  if (isMobile(req.headers["user-agent"])) {
    res.redirect('//m.' + req.hostname + req.path);
  } else {
    next()
  }
}

route.js

require('./isMobile');

router.get("/components", isMobile, function(req, res) {
  res.render("components");
});

Alternatively, you could use the middleware so it applies to all your routes.

app.js

require('./isMobile');

app.use(isMobile)
// Load routes here