11import { captureException } from '@sentry/browser' ;
22import { Transaction , TransactionContext } from '@sentry/types' ;
3- import VueRouter from 'vue-router' ;
4-
5- export type Action = 'PUSH' | 'REPLACE' | 'POP' ;
63
74export type VueRouterInstrumentation = < T extends Transaction > (
85 startTransaction : ( context : TransactionContext ) => T | undefined ,
96 startTransactionOnPageLoad ?: boolean ,
107 startTransactionOnLocationChange ?: boolean ,
118) => void ;
129
13- let firstLoad = true ;
10+ // This is not great, but kinda necessary to make it work with VueRouter@3 and VueRouter@4 at the same time.
11+ type Route = {
12+ params : any ;
13+ query : any ;
14+ name : any ;
15+ path : any ;
16+ matched : any [ ] ;
17+ } ;
18+ interface VueRouter {
19+ onError : ( fn : ( err : Error ) => void ) => void ;
20+ beforeEach : ( fn : ( to : Route , from : Route , next : ( ) => void ) => void ) => void ;
21+ }
1422
1523/**
1624 * Creates routing instrumentation for Vue Router v2
@@ -25,17 +33,24 @@ export function vueRouterInstrumentation(router: VueRouter): VueRouterInstrument
2533 ) => {
2634 router . onError ( error => captureException ( error ) ) ;
2735
28- const tags = {
29- 'routing.instrumentation' : 'vue-router' ,
30- } ;
36+ router . beforeEach ( ( to , from , next ) => {
37+ // According to docs we could use `from === VueRouter.START_LOCATION` but I couldnt get it working for Vue 2
38+ // https://router.vuejs.org/api/#router-start-location
39+ // https://next.router.vuejs.org/api/#start-location
3140
32- router . beforeEach ( ( to , _from , next ) => {
41+ // Vue2 - null
42+ // Vue3 - undefined
43+ const isPageLoadNavigation = from . name == null && from . matched . length === 0 ;
44+
45+ const tags = {
46+ 'routing.instrumentation' : 'vue-router' ,
47+ } ;
3348 const data = {
3449 params : to . params ,
3550 query : to . query ,
3651 } ;
3752
38- if ( startTransactionOnPageLoad && firstLoad ) {
53+ if ( startTransactionOnPageLoad && isPageLoadNavigation ) {
3954 startTransaction ( {
4055 name : to . name || to . path ,
4156 op : 'pageload' ,
@@ -44,7 +59,7 @@ export function vueRouterInstrumentation(router: VueRouter): VueRouterInstrument
4459 } ) ;
4560 }
4661
47- if ( startTransactionOnLocationChange && ! firstLoad ) {
62+ if ( startTransactionOnLocationChange && ! isPageLoadNavigation ) {
4863 startTransaction ( {
4964 name : to . name || to . matched [ 0 ] . path || to . path ,
5065 op : 'navigation' ,
@@ -53,7 +68,6 @@ export function vueRouterInstrumentation(router: VueRouter): VueRouterInstrument
5368 } ) ;
5469 }
5570
56- firstLoad = false ;
5771 next ( ) ;
5872 } ) ;
5973 } ;
0 commit comments