segmentio / snippet Goto Github PK
View Code? Open in Web Editor NEWRender the analytics.js snippet.
License: MIT License
Render the analytics.js snippet.
License: MIT License
Hi there.
I've noticed calls to track
and identify
getting lost on our site, which uses the Segment Intercom integration. The calls in question are taking place in-between loading of analytics.min.js
and loading of the Intercom scripts.
I believe this to be because queued events are dequeued when the analytics.min.js
script finishes loading, but the API queues from the snippet remain in place until integration scripts finish loading. I found some calls still in the queue at the point that the snippet's ready
callback is run.
Here's an illustration of these events that I am logging out to the JavaScript console to debug them:
I've gotten around this by changing the ready
callback to the following:
analytics.ready(function () {
// KF: Dequeue events queued while waiting for scripts to load
// This fixes an issue where events queued after Segment script
// loads, but before the Intercom script loads, are ignored.
while (analytics && analytics.length > 0) {
var args = analytics.shift();
var method = args.shift();
if (window.analytics[method]) window.analytics[method].apply(window.analytics, args);
}
for (var i = 0; i < methods.length; i++) {
var key = methods[i];
analytics[key] = window.analytics[key];
}
});
Happy to discuss this problem or provide a pull request.
Thanks!
I would love to see TypeScript declarations for this :-)
Hello everyone,
First of all thanks a lot for all the great work here !
I've been using the segment snippet in a nextjs application and everything is going well. (I followed nextjs official integration process)
However, I've found myself trying to send some url parameters as event properties in the default page
call for 2 main reasons
myproject.com/foo&label=ABC
and myproject.com/foo&label=DEF
makes it impossible to analyze the data without struggle or ETLAny idea how I can get out of this ?
Cheers ๐
The npm package contains a lot of files. These files are not used from the users. There should be no dev configs like linter or circle ci files in the production output.
Me as a user I want to access the min
and max
function. The rest does not matter to me. Plus the package.json
, types.d.ts
and the Readme.md
of course.
With the following output the package will do the same as before and will get lighter which is always a nice thing ๐
(history.md
could also be removed but thats a matter of taste)
Hello!
I wanted to know if adding an option in order to allow user to register a custom callback for the ready
method would make sense for you?
I can help with a PR for this, if you want to!
Thanks!
I know that there are just three page options as 'category' , 'name' and 'properties'
but I wanna put into common fields using 'options' properties in page call like 'context' , 'integrations'.
but I can just use 'integrations' when I use load call, not page call.
and even cannot use any other common fields.
can you let me put common fields into page call when I use snippet??
Thanks.
Just tested out 4.14.0 and got this error Error: Cannot find module '../dist/max.template'
. Seems like the dist/
folder isn't included in the build.
Running build.js
generates dist/
and fixes the error.
we gets lots of support tickets for it
since there's analytics.prototype.push()
.
Hi!
I updated from 4.13.1
to 4.14.2
, and now when we run tsc --noEmit
, the following error is displayed
./node_modules/@segment/snippet/types.d.ts:12:13 - error TS2411: Property 'All' of type 'boolean | undefined' is not assignable to string index type 'boolean'.
12 All?: boolean
~~~
We are using typescript 3.8.3
.. a bit dated, but perhaps there is a mistake in this type definition?
I was looking through the source to see which version was support and saw the following
Line 60 in 12e15bc
Unless the v2 source ends up being available at the v1 path then I assume that there needs to be an update to support the v2 source?
Any word on if there is an intent to do this?
some people want this snippet versioned so they can add it via bower, to minify it etc..
/cc @ianstormtaylor
There doesn't appear to be a way to provide options for the load call. See here.
Similar to page options, how about something like this?
var snippet = require('@segment/snippet');
var contents = snippet.max({
host: 'cdn.segment.com',
apiKey: '03fwkuu3',
page: {
category: 'Docs',
name: 'Integrations',
properties: {
foo: 'bar'
}
},
load: {
integrations: {
All: false,
AdRoll: true
}
}
});
window.analytics.SNIPPET_VERSION="2.0.8",
window.analytics.load("YOUR_WRITE_KEY");
window.analytics.page();
</script>
not sure but i think people add the snippet to angular's view or whatever and it get's re-executed, throwing max call stack exceeded
.
in case analytics.js fails to load (sometimes adblock blocks it) it would be good if the snippet had some logic to make sure callbacks to track
/identify
etc always got called even if the script fails to load
Thanks!
Currently, snippet does not support the 'options' arg.
My use case involves anonymizing a user's IP address, which requires passing options.context.ip
to Page calls, but I am unable to do so because the library does not support the options
arg.
Is there a reason why this is not supported?
Hi!
We are using Nextjs 11.1.2
and since the version 4.15.0
of the snippet we face the following issue:
browser.ts:75 Failed to load settings SyntaxError: Unexpected token < in JSON at position 0
[analytics.js] Failed to load Analytics.js SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
Downgrading to
4.13.2
solves it.
The error seems to come from this part of the code:
export function loadLegacySettings(writeKey: string): Promise<LegacySettings> {
const cdn = window.analytics?._cdn ?? getCDN()
return fetch(`${cdn}/v1/projects/${writeKey}/settings`)
.then((res) => res.json())
.catch((err) => {
console.warn('Failed to load settings', err)
throw err
})
}
We saw in the changelog something related to it in https://github.com/segmentio/snippet/pull/73/files
Do we have to upgrade something else on our end to make the 4.15.0
happy?
Cheers!
Segment seems to block the main thread for 300+ ms
We are using async
tags though. Any ideas?
// Segment
renderSegmentSnippet() {
const opts = {
apiKey: env.SEGMENT_WRITE_KEY,
page: true,
};
if (process.env.NODE_ENV === "development") {
return snippet.max(opts);
}
return snippet.min(opts);
}
...
{/* Segment */}
<script
async
dangerouslySetInnerHTML={{ __html: this.renderSegmentSnippet() }}
/>
hey guys! I'm having some issues integrating the library in my React application...it fails when I try to build my app using webpack...here is my code:
import React, { PropTypes, Component } from 'react'
import segmentioSnippet from 'segmentio-snippet'
export default class Analytics extends Component {
static propTypes = {
host: PropTypes.string,
key: PropTypes.string.isRequired,
}
static defaultProps = {
host: 'cdn.segment.com',
}
render() {
const { key, host } = this.props
// Generate snippet code
const snippet = segmentioSnippet.min({
apiKey: key,
host,
})
// Inject code into script tag
return (
<script type="text/javascript">{snippet}</script>
)
}
}
Here's part of the error log:
frontend โ WARNING in ./~/handlebars/lib/index.js
frontend โ require.extensions is not supported by webpack. Use a loader instead.
frontend โ
frontend โ WARNING in ./~/handlebars/lib/index.js
frontend โ require.extensions is not supported by webpack. Use a loader instead.
frontend โ
frontend โ WARNING in ./~/handlebars/lib/index.js
frontend โ require.extensions is not supported by webpack. Use a loader instead.
frontend โ
frontend โ ERROR in ./~/segmentio-snippet/lib/index.js
frontend โ Module not found: Error: Cannot resolve module 'fs' in /usr/src/app/node_modules/segmentio-snippet/lib
frontend โ @ ./~/segmentio-snippet/lib/index.js 7:11-24 12:9-22
frontend โ
frontend โ ERROR in ./~/handlebars/lib/index.js
frontend โ Module not found: Error: Cannot resolve module 'fs' in /usr/src/app/node_modules/handlebars/lib
frontend โ @ ./~/handlebars/lib/index.js 19:13-26
Any help will be very welcome
We have segment built into a NextJS react app and we're having trouble with duplicate page()
calls on the initial load when a user lands on the site.
AFAICS, the core analytics.js segmentio/analytics.js#558 suggests that initialPageview
can be disabled by setting it to false
- however, from looking at the docs + code I'm not sure this is propagated to analytics config (which defaults to false anyway).
Furthermore, looking at window.analytics.options
on the browser, it's set to false.
Initial Page View (Result)
analytics.page({
path: '/',
referrer: 'https://www.google.com/',
search: '',
title: 'Foobar',
url: 'https://www.mysite.com./'
});
Duplicate Page View on "root" (Result)
analytics.page('/', {
name: '/',
path: '/',
referrer: 'https://www.google.com/',
search: '',
title: 'Foobar',
url: 'https://www.mysite.com./'
});
Is there a way to eliminate this duplication via this library?
At work we currently use this module to render (server side) the analytics script in a Node based application. We usually toggle certain features based on configurable runtime flags. On of those flags is if the snippet should be render minified or not. Having a single method which allow for a simple toggle is convenient in this case:
const { include } = require('@segment/snippet');
const snippet = include({
minified: Boolean,
...allOtherPropsAvailable,
});
Is that something you would consider adding?
Hi,
Could you possibly support importing only min or max, i.e:
import min from "@segment/snippet/min";
As currently when compiling since both are imported in lib/index.js, bundles end up including both scripts in their source code.
Cheers
Our Sentry instance has detected an error in the snippet rendered by this library: SyntaxError: Unexpected end of input
.
This is the stack trace:
The user runs into this bug as soon as they visit any page on our site which injects the Segment snippet.
Here is a brief demographic overview for users getting this bug on our site:
If I understand correctly, this repository and approach to load analytics.js have been deprecated in favor of Analytics 2.0.
However, there is no clear indication on this repository and it creates confusion when we land here after googling "Segment snippet" ๐
It would be very helpful if this repository had been archived and/or the readme would link to https://github.com/segmentio/analytics-next/ as the new official way of using Segment.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.