NodeJS: TypeError: Cannot read property 'user-agent' of undefined

Im getting the following error:

TypeError: Cannot read property 'user-agent' of undefined
    at /home/ubuntu/node/server.js:312:154

At line 312 I have this code:

var p = require('ua-parser');
console.log(p.parseUA(spark.headers['user-agent']).toString());

Any ideas how to avoid the error? Its causing forever to restart.

Edit

var p = require('ua-parser');

primus.on('connection', function (spark) {

    spark.on('register', function (data) {
        console.log(p.parseUA(spark.headers['user-agent']).toString());
    });

 });

Just like the error indicated. "spark.headers" is "undefined".

If the headers is not set, it is "undefined" and accessing a property of it will cause the exception.