Search code examples
node.jsserver-side

How to distinguish calls from mobile app and web browser in Node Js?


I'm still a bit new to server-side programming, and have decided to start practicing mobile app programming. In NodeJS you use the post and get methods, however, I would like to be able to distinguish if a mobile app requested (to send it JSON instead of HTML) or if a web browser requested (to send it HTML) a page.

How do you do this?

Do you achieve this by having separate urls (one for the apps and one for the browsers)? If so, I would like a bit of explanation.

Thank you!


Solution

  • You haven't said how you're building your server-side app, but the normal way to do this is using the 'user agent' indicated by the client.

    If you're using express, there are modules that make this easy, like https://www.npmjs.com/package/express-useragent

    Which gives you a structure that includes a field isMobile in req parameter:

    // req.useragent 
    {
      "isMobile":false,
      "isDesktop":true,
      "isBot":false,
      .....
      "browser":"Chrome",
      "version":"17.0.963.79",
      "os":"Windows 7",
      "platform":"Microsoft Windows",
      "source":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79..."
    }