Advanced Sentry instrumentation for Lit-based SPAs, with per-component render tracing and robust SPA navigation support.
- Per-component render spans: Every Lit component render is traced as a Sentry span, including async/conditional children.
- SPA navigation transactions: Each navigation (route change) is tracked as a Sentry transaction.
- Route context: All spans include the current route for easy filtering and debugging.
- No private data: Sentry DSN is read from an environment variable, never hardcoded.
-
Clone the repo:
git clone https://github.com/Angelodaniel/lit-components-custom-instrumentation.git cd lit-components-custom-instrumentation -
Set your Sentry DSN:
- Create a
.envfile in the project root:VITE_SENTRY_DSN=<your-dsn-here> - Never commit your DSN to the repo.
- Create a
-
Install dependencies and run:
npm install npm run dev
-
Open the app:
Visit http://localhost:3000 in your browser.
- Sentry is initialized before any components are loaded.
- SPA navigation (route changes) triggers a new Sentry transaction using
Sentry.startSpan({ forceTransaction: true, op: 'navigation' }). - Each Lit component (including children and grandchildren) extends
InstrumentedLitElement, which:- Starts a custom span for each render.
- Waits for all async/conditional children to finish rendering before ending the span.
- Includes the current route in the span attributes.
-
DSN Security:
Always use an environment variable for your DSN. Never commit your real DSN to a public repo. -
Sentry v9.x API:
- Use
Sentry.startSpanwithforceTransaction: truefor navigation transactions. - Use the
window.__SENTRY__.hubworkaround to set the active span in the browser.
- Use
-
SPA Navigation:
By default, all navigation transactions are grouped under the same trace. If you want each navigation to start a new trace, you must generate and provide a newtraceId(see Sentry docs). -
Lit async/conditional children:
TheInstrumentedLitElementuses both aMutationObserverand recursiveupdateCompletechecks to ensure spans only end when the entire subtree is rendered. -
Performance:
Instrumentation adds a small overhead. For production, setdebug: falsein Sentry config.