Search code examples
mysqlbrowserdatabase-designuser-agent

How long should I make database field to save user agent strings?


I am modifying a login system and have been tasked to log all authentication requests for security purposes.

One of my plans is to record the user agent strings of incoming requests and translate them into readable displays, such as Request from: (Chrome/Windows) or Request from: (Firefox/Mac) whenever the user asks for this information. What length should my varchar field be in MySQL?

Is it necessary to have the entire user agent string to accurately determine the client's browser and operating system information in the future, or is there a specification for user agents that enables me to extract only a portion of it and discard the rest as unnecessary information?


Solution

  • Short answer: even if it's arbitrarily large, some User-Agents will still get cut off.

    Longer answer: Unless you plan on putting an index on the User-Agent (I don't see why you would if it's only for record/display purposes), there's no reason to use a VarChar instead of a Text field which is long enough.

    Alternatively, you could seek out a User-Agent parsing library which turns the string into something more useful such as "Chrome/Windows" or "Safari/iPhone" in which case you could reasonably use a shorter VarChar value.

    There is absolutely no specification for User-Agent strings. They are completely arbitrary although many adhere to a few general patterns that you cannot always assume for all User Agents.

    In summary, your 3 options are:

    • get a library to parse them meaningfully
    • pick an arbitrary varchar length and accept that some will be cut off
    • use a text field