Device Detection with the User-Agent

Derek Oware
2 min readFeb 15, 2021

Have you ever wanted to implement a feature for a specific platform or device? Like show a screen or some content to mobile users only or execute a different an action based on the user’s device

I usually come across contents on sites that are clearly meant for mobile users only while I browse on desktop.

User-Agent can be helpful in this situation.

MDN defines the user agent as

The User-Agent request header is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.

A common format for a user agent string looks like:

Mozilla/5.0 (<system-information>) <platform> (<platform-details>) <extensions>

Detect User’s device

To know if a user is on mobile, look for “Mobi” in the user agent string as you can see in the example below

The example above results in

Demo example on a desktop device

Demo example on a mobile device

Test in your browser

To test this in your browser, open the developer tools and click on the ‘toggle device’ icon. Refresh your page for changes to apply

Practical Example

Here is a practical example of this in my React application.
I used this in a federated login

Conclusion

Obviously, you can tell this is not meant to replace media queries, however, this can be very useful in your projects. Media Queries are mainly used for responsive pages whereas this method is for device-specific features or content. This is mainly useful when you want your mobile app to behave differently from the desktop version. You can use this to give mobile users app-like experience especially when dealing with Progressive Web Apps

Read more from MDN docs

--

--

Derek Oware

Self-taught full stack web developer (mostly front end). I really enjoy experimenting with web technologies and demystifying concepts