README SENTRY - nself-org/nchat GitHub Wiki
This guide explains how to set up Sentry error tracking and performance monitoring for nself-chat (nchat) in production environments.
Sentry is configured for comprehensive error tracking across all runtime environments:
- Browser/Client-side: Track frontend errors, user interactions, and performance
- Node.js/Server-side: Track API errors, server component errors, and backend issues
- Edge Runtime: Track middleware and edge function errors
- Sign up at sentry.io
- Create a new organization (or use existing)
- Create a new project:
- Platform: Next.js
- Alert frequency: On every new issue (recommended for production)
After creating your project, you'll receive a DSN (Data Source Name) that looks like:
https://[key]@[org].ingest.sentry.io/[project]
Add the following to your production environment variables:
Required:
NEXT_PUBLIC_SENTRY_DSN=https://[key]@[org].ingest.sentry.io/[project]Optional (for sourcemap uploads):
SENTRY_ORG=your-org-slug
SENTRY_PROJECT=your-project-slug
SENTRY_AUTH_TOKEN=your-auth-tokenFor release tracking:
NEXT_PUBLIC_RELEASE_VERSION=0.5.0 # Or use git commit SHABy default, Sentry is disabled in development to avoid noise. To enable:
SENTRY_ENABLE_DEV=true
NEXT_PUBLIC_SENTRY_ENABLE_DEV=truesrc/
├── instrumentation.ts # Entry point for Next.js instrumentation
├── instrumentation.node.ts # Server-side (Node.js) configuration
├── instrumentation.edge.ts # Edge runtime configuration
├── sentry.client.config.ts # Client-side (Browser) configuration
└── lib/
└── sentry-utils.ts # Helper functions for Sentry operations
-
Next.js 15 Instrumentation Hook: The
instrumentation.tsfile is automatically loaded by Next.js - Runtime Detection: Automatically detects and loads the correct configuration based on runtime
- Client-side Initialization: The client config is imported in the root layout
- Automatic Error Capture: All unhandled errors are captured automatically
- Source Maps: Production builds include source maps for readable stack traces
- Context: Errors include user context, breadcrumbs, and environment details
- Transaction Tracing: Track request/response times
-
Sample Rates: Configurable sampling to control volume and costs
- Production: 10% of transactions
- Development: 100% of transactions
- Visual Debugging: See what users did before an error occurred
- Privacy-first: All text and media are masked by default
-
Sample Rates:
- Normal sessions: 1% in production
- Error sessions: 50% in production
Track user actions leading up to errors:
- Console logs (dev only)
- DOM events (clicks, inputs)
- Network requests (fetch, XHR)
- Navigation history
- User actions
All configurations include automatic filtering of sensitive data:
Filtered Headers:
authorizationcookiex-api-key
Filtered Fields:
passwordtokensecretapiKeycreditCardssn
User Opt-out:
Users can opt-out by setting localStorage.setItem('sentry-opt-out', 'true')
nself-chat provides utility functions to simplify Sentry operations. Import them from @/lib/sentry-utils:
import { setSentryUser } from '@/lib/sentry-utils'
// On user login
setSentryUser({
id: user.id,
email: user.email,
username: user.username,
role: user.role,
})
// On logout
setSentryUser(null)import { captureError } from '@/lib/sentry-utils'
try {
await riskyOperation()
} catch (error) {
captureError(error, {
tags: {
section: 'chat',
action: 'send-message',
},
extra: {
channelId: channel.id,
messageLength: message.length,
},
})
}import { captureMessage } from '@/lib/sentry-utils'
captureMessage('Payment processing started', 'info', {
tags: { feature: 'payments' },
extra: { amount: 99.99 },
})import { addSentryBreadcrumb } from '@/lib/sentry-utils'
addSentryBreadcrumb('auth', 'User logged in', {
userId: user.id,
method: 'email',
})import { setSentryContext } from '@/lib/sentry-utils'
setSentryContext('channel', {
id: channel.id,
type: channel.type,
memberCount: channel.memberCount,
})import { startSentryTransaction } from '@/lib/sentry-utils'
const transaction = startSentryTransaction('task', 'Process Bulk Upload')
try {
await processBulkUpload(files)
transaction.setStatus('ok')
} catch (error) {
transaction.setStatus('internal_error')
throw error
} finally {
transaction.finish()
}Adjust in the respective configuration files:
Server-side (instrumentation.node.ts):
tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0Client-side (sentry.client.config.ts):
tracesSampleRate: 0.1, // 10% of transactions
replaysSessionSampleRate: 0.01, // 1% of sessions
replaysOnErrorSampleRate: 0.5, // 50% of error sessionsCommon noisy errors are automatically ignored:
- Browser extension errors
- Network failures (expected)
- Navigation cancellations
- Next.js redirects
- ResizeObserver errors
Add custom patterns in the ignoreErrors array.
All events are tagged with:
-
runtime:browser,nodejs, oredge -
nextjs:15 -
app:nself-chat
Add custom tags in initialScope.tags.
Sentry works out-of-the-box on Vercel:
- Add environment variables in Vercel dashboard
- Enable source maps in
next.config.js(already enabled) - Deploy normally
Environment variables can be passed during container runtime:
docker run \
-e NEXT_PUBLIC_SENTRY_DSN=your-dsn \
-e SENTRY_ORG=your-org \
-e SENTRY_PROJECT=your-project \
nself-chat:latestAdd secrets to your deployment:
apiVersion: v1
kind: Secret
metadata:
name: sentry-secrets
type: Opaque
stringData:
NEXT_PUBLIC_SENTRY_DSN: 'https://[key]@[org].ingest.sentry.io/[project]'
SENTRY_AUTH_TOKEN: 'your-auth-token'Reference in deployment:
env:
- name: NEXT_PUBLIC_SENTRY_DSN
valueFrom:
secretKeyRef:
name: sentry-secrets
key: NEXT_PUBLIC_SENTRY_DSNSource maps are automatically uploaded during production builds if configured:
- Create a Sentry auth token: sentry.io/settings/account/api/auth-tokens/
- Add to environment:
SENTRY_AUTH_TOKEN=your-token SENTRY_ORG=your-org SENTRY_PROJECT=your-project
The Sentry Next.js SDK will automatically upload source maps during next build.
Set different DSNs for staging and production:
# Staging
NEXT_PUBLIC_SENTRY_DSN=https://[email protected]/staging-project
# Production
NEXT_PUBLIC_SENTRY_DSN=https://[email protected]/prod-projectConfigure alerts in Sentry dashboard:
- Immediate: Critical errors, payment failures
- Hourly digest: General errors
- Daily digest: Performance issues
Set performance budgets in Sentry:
- Page load: < 2s
- API responses: < 500ms
- Database queries: < 100ms
Schedule regular reviews:
- Weekly: New error types
- Monthly: Performance trends
- Quarterly: User impact analysis
Always add relevant context to errors:
import { setSentryContext } from '@/lib/sentry-utils'
setSentryContext('channel', {
id: channel.id,
type: channel.type,
memberCount: channel.memberCount,
})- Check DSN is correctly set
- Verify environment is not
test - Confirm
SENTRY_ENABLE_DEVis true (if in development) - Check browser console for initialization log
- Adjust sample rates
- Add more patterns to
ignoreErrors - Filter specific URLs with
denyUrls
- Verify
SENTRY_AUTH_TOKENis set - Check build logs for upload confirmation
- Ensure project name matches in Sentry dashboard
- Reduce sample rates
- Disable Session Replay
- Limit breadcrumb collection
Sentry pricing is based on events and transactions:
- Adjust Sample Rates: Lower rates = lower costs
-
Filter Noise: Use
ignoreErrorsandbeforeSend - Quotas: Set monthly quotas in Sentry dashboard
- Spike Protection: Enable in project settings
For issues specific to nself-chat Sentry integration:
- Create an issue: GitHub Issues
- Email: [email protected]
- Discord: nself Community