segmentio / analytics-node

The hassle-free way to integrate analytics into any node application.

Home Page:https://segment.com/libraries/node

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

analytics-node doesn't work in Chrome/Firefox extension environments as advertised

conoremclaughlin opened this issue · comments

commented

This page suggests using analytics-node as a library:

https://segment.com/docs/connections/sources/plugins/

But a number of errors are thrown from any call to analytics:

utils.inherits // I ended up mocking this to see if I could get the library to work as I've done with other node libraries
Buffer

Example error:

Uncaught (in promise) ReferenceError: Buffer is not defined
    at validateGenericEvent (VM1121 background.js:17376)
    at looselyValidateEvent (VM1121 background.js:17278)
    at Analytics._validate (VM1121 background.js:17942)
    at Analytics.identify (VM1121 background.js:17954)
    at _callee$ (VM1121 background.js:146741)
    at tryCatch (VM1121 background.js:11299)
    at Generator.invoke [as _invoke] (VM1121 background.js:11529)
    at Generator.next (VM1121 background.js:11354)
    at asyncGeneratorStep (VM1121 background.js:10628)
    at _next (VM1121 background.js:10650)

Per the question asked in the comments of this Stack Overflow question:

https://stackoverflow.com/questions/27912213/using-segment-io-in-chrome-extension

How should we proceed with analytics.js 2.0?

@conoremclaughlin If you are using webpack, you can probably polyfill node globals like Buffer. I think Webpack 4 should do this internally, and Webpack 5 via a plugin.

@conoremclaughlin Hello!
Did you try adding the polyfill as suggested by @pooyaj ?

@conoremclaughlin If you have any further issue regarding this, please feel free to re-open this issue. Thank you

commented

I did! And it worked like a charm for Webpack v4. Thanks for the help :) I've got other polyfills but the below snippet was required for my webpack configuration. Leaving this here for anyone else who stumbles along this issue:

// c: mocking more node in order to run analytics-node from segment
// @see https://v4.webpack.js.org/configuration/node/
// @see https://github.com/segmentio/analytics-node/issues/282
config.node = config.node || {};
config.node.Buffer = true;

module.exports = config;

Awesome! Thank you!