Skip to content

Conversation

@pingSubhajit
Copy link
Owner

@pingSubhajit pingSubhajit commented Jul 24, 2025

Issue:

LET-64 | logic: Identify users in Sentry from NextJS service through Clerk's SDK

Description:

Enhancing the Sentry integration in the Next.js frontend to effectively identify users using Clerk's authentication SDK.

Changes Made:

  • Retrieve user information from Clerk's SDK post successful authentication.
  • Implement Sentry.setUser() method to set user context in Sentry with relevant attributes.
  • Test error triggering while logged in to verify correct user association in Sentry.
  • Ensure secure handling of sensitive user data and adherence to privacy best practices.
  • Add custom tags to Sentry events for additional context.
  • Handle cases of non-logged-in users gracefully.

Closing Note:

This PR is crucial as it enables associating errors and performance data in Sentry with specific users, facilitating effective debugging, targeted issue resolution, and improved user experience.

Summary by CodeRabbit

  • New Features

    • Integrated enhanced Sentry error tracking with user context, including support for authenticated and anonymous users.
    • Added custom event fingerprinting and user segmentation to improve error grouping and diagnostics.
  • Chores

    • Updated Sentry configuration for improved environment detection and event handling.
    • Introduced a new provider to manage user context for error tracking within the app layout.

@vercel
Copy link

vercel bot commented Jul 24, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
letraz ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 24, 2025 4:42am

@coderabbitai
Copy link

coderabbitai bot commented Jul 24, 2025

"""

Walkthrough

A new SentryUserProvider React component is introduced to integrate Clerk authentication with Sentry user context and tagging. The root layout is updated to wrap existing providers with this new provider. Both client and server Sentry configurations are enhanced with a beforeSend hook to enrich event data with user-specific context and custom fingerprints.

Changes

File(s) Change Summary
app/layout.tsx Imported and wrapped children/providers with new SentryUserProvider in the root layout.
components/providers/SentryUserProvider.tsx Added new exported SentryUserProvider component integrating Clerk user data with Sentry context/tags.
sentry.client.config.ts, sentry.server.config.ts Added beforeSend hooks to enrich Sentry events with user info, custom fingerprint, and extra metadata.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ClerkProvider
    participant SentryUserProvider
    participant Sentry

    User->>ClerkProvider: Authenticate/Login
    ClerkProvider-->>SentryUserProvider: Provide user/auth data
    SentryUserProvider->>Sentry: Set user context/tags
    SentryUserProvider->>Sentry: On logout, clear user context
    Sentry->>Sentry: On error event, run beforeSend hook
    Sentry->>Sentry: Add fingerprint & user metadata to event
    Sentry->>Sentry: Send enriched event
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related issues

Suggested reviewers

  • sourabhrathourr

Poem

In the warren of code, a provider appears,
Linking Sentry and Clerk, to lessen our fears.
Now errors have faces, not just a trace,
With fingerprints unique in every case.
Hopping through logs with a bunny’s delight,
Debugging is clearer—oh, what a sight!
🐇✨
"""

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f008eb5 and c3251b3.

📒 Files selected for processing (3)
  • components/providers/SentryUserProvider.tsx (1 hunks)
  • sentry.client.config.ts (1 hunks)
  • sentry.server.config.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • components/providers/SentryUserProvider.tsx
  • sentry.server.config.ts
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: pingSubhajit
PR: pingSubhajit/letraz#98
File: lib/education/actions.ts:36-47
Timestamp: 2025-01-31T08:29:21.935Z
Learning: During the migration phase of the NextJS frontend to use the dedicated backend server (LET-39), error handling improvements should be deferred as they are not a priority.
Learnt from: pingSubhajit
PR: pingSubhajit/letraz#98
File: lib/user-info/actions.ts:11-28
Timestamp: 2025-02-01T05:41:08.418Z
Learning: Functions in the codebase that use `auth()` from Clerk (e.g., `addOrUpdateUserInfoToDB`) don't need session null checks as they are only called when a session is guaranteed to be present, with session validation being handled on the consumer side.
sentry.client.config.ts (3)

Learnt from: pingSubhajit
PR: #98
File: lib/resume/actions.ts:61-76
Timestamp: 2025-01-31T08:35:40.680Z
Learning: Error handling improvements should not be suggested during the NextJS frontend lib methods migration phase as it's not a priority. The focus should be on completing the core migration first.

Learnt from: pingSubhajit
PR: #98
File: lib/education/actions.ts:55-65
Timestamp: 2025-01-31T08:29:35.781Z
Learning: Error handling improvements should not be suggested during the migration phase of the NextJS frontend to dedicated backend server, as it's not a priority at this stage.

Learnt from: pingSubhajit
PR: #135
File: components/resume/ReorderableSections.tsx:374-375
Timestamp: 2025-07-06T16:20:32.913Z
Learning: In components/resume/ReorderableSections.tsx, the activeGroupId type casting to string is safe because the group drag context uses groupOrder (which contains strings) as sortable items. When a group drag starts, active.id will always be one of the string values from groupOrder, so the type casting from UniqueIdentifier to string is validated by the implementation context.

🔇 Additional comments (2)
sentry.client.config.ts (2)

39-40: LGTM: Improved debug configuration alignment.

The change from process.env.VERCEL_ENV !== 'production' to process.env.NODE_ENV === 'development' for the debug flag is more conventional and aligns better with standard Node.js environment practices while maintaining the separate environment setting from VERCEL_ENV.


42-55: LGTM: Well-implemented user context enrichment hook.

The beforeSend hook effectively fulfills the PR objective of identifying users in Sentry events. The implementation includes:

  • Proper conditional checking for user presence before processing
  • Custom fingerprinting that combines default behavior with user-specific identification
  • Safe fallback to 'anonymous' for missing user IDs
  • User segment metadata enrichment in extra context
  • Correct type assertion handling (addressing the previous review feedback)

The hook will work seamlessly with the SentryUserProvider component to associate errors with authenticated Clerk users, enabling better debugging and issue resolution as intended.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch subhajit/let-64-logic-identify-users-in-sentry-from-nextjs-service-through

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
components/providers/SentryUserProvider.tsx (2)

19-56: Consider consolidating user context logic and review PII handling.

The main authentication effect correctly handles user context setting, but there are opportunities for improvement:

  1. PII Consideration: Email addresses are considered PII. Consider using a hashed version or just the domain:
-				email: user.emailAddresses[0]?.emailAddress,
+				email: user.emailAddresses[0]?.emailAddress?.replace(/^[^@]+/, '***'),
  1. Reduce Duplication: Setting both getCurrentScope() and global scope might be redundant. The global setUser/setTag calls should be sufficient:
-			// Set user context on both current scope and global scope for maximum compatibility
-			Sentry.getCurrentScope().setUser(sentryUser)
			Sentry.setUser(sentryUser)
-
-			// Set additional context tags
-			Sentry.getCurrentScope().setTag('user.onboardingComplete', user.publicMetadata?.onboardingComplete || false)
-			Sentry.getCurrentScope().setTag('user.currentStep', user.publicMetadata?.currentOnboardingStep || 'unknown')
			Sentry.setTag('user.onboardingComplete', user.publicMetadata?.onboardingComplete || false)
			Sentry.setTag('user.currentStep', user.publicMetadata?.currentOnboardingStep || 'unknown')

75-83: Improve cleanup logic to be more explicit.

The cleanup effect only clears user context when userId is falsy, but it should clear context regardless on unmount to prevent stale data.

	// Handle cleanup when component unmounts
	useEffect(() => {
		return () => {
			// Clear user context on unmount to prevent stale data
-			if (!userId) {
				Sentry.setUser(null)
-			}
		}
-	}, [userId])
+	}, [])

This ensures consistent cleanup regardless of the current auth state.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fe39651 and f008eb5.

📒 Files selected for processing (4)
  • app/layout.tsx (2 hunks)
  • components/providers/SentryUserProvider.tsx (1 hunks)
  • sentry.client.config.ts (1 hunks)
  • sentry.server.config.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: pingSubhajit
PR: pingSubhajit/letraz#98
File: lib/education/actions.ts:36-47
Timestamp: 2025-01-31T08:29:21.935Z
Learning: During the migration phase of the NextJS frontend to use the dedicated backend server (LET-39), error handling improvements should be deferred as they are not a priority.
Learnt from: pingSubhajit
PR: pingSubhajit/letraz#98
File: lib/user-info/actions.ts:11-28
Timestamp: 2025-02-01T05:41:08.418Z
Learning: Functions in the codebase that use `auth()` from Clerk (e.g., `addOrUpdateUserInfoToDB`) don't need session null checks as they are only called when a session is guaranteed to be present, with session validation being handled on the consumer side.
app/layout.tsx (2)

Learnt from: pingSubhajit
PR: #145
File: package.json:28-28
Timestamp: 2025-07-11T17:30:08.789Z
Learning: The @knocklabs/react package includes all required Knock notification functionality including notification feed components, eliminating the need for separate packages like @knocklabs/react-notification-feed and @knocklabs/client.

Learnt from: pingSubhajit
PR: #145
File: components/notifications/NotificationBell.tsx:11-13
Timestamp: 2025-07-11T17:19:06.970Z
Learning: The codebase uses error boundaries to handle runtime errors from components that depend on external services like Knock, rather than adding conditional safety checks around hook calls which would violate the Rules of React.

🧬 Code Graph Analysis (1)
app/layout.tsx (4)
components/providers/SentryUserProvider.tsx (1)
  • SentryUserProvider (15-86)
components/providers/KnockProvider.tsx (1)
  • KnockProvider (29-58)
components/ui/tooltip.tsx (1)
  • TooltipProvider (30-30)
components/ui/sonner.tsx (1)
  • Toaster (28-28)
🔇 Additional comments (5)
app/layout.tsx (2)

13-13: LGTM! Correct import and provider integration.

The import follows the established pattern and the provider is correctly positioned in the component hierarchy.


39-48: Provider hierarchy verified – SentryUserProvider correctly nested inside ClerkProvider

SentryUserProvider is wrapped by <ClerkProvider> in app/layout.tsx (lines 32–53), so user context will propagate as intended. No further changes required.

sentry.server.config.ts (1)

17-17: LGTM! Debug flag correctly set for production.

The debug flag is appropriately disabled for production environments.

components/providers/SentryUserProvider.tsx (1)

1-10: LGTM! Proper component setup with correct client directive.

The component is correctly marked as client-side with proper imports and interface definition.

sentry.client.config.ts (1)

39-40: LGTM! Improved debug flag logic.

Using NODE_ENV === 'development' for the debug flag is more appropriate than checking the Vercel environment, as it aligns with standard Node.js development practices.

Copy link
Collaborator

@sourabhrathourr sourabhrathourr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Observation: This PR adds user identification in Sentry using Clerk’s SDK for the Next.js service. By associating Sentry events with authenticated users, it enhances error monitoring and debugging.

Remark: The PR is ready to be merged.

@pingSubhajit pingSubhajit merged commit 744eec3 into main Jul 25, 2025
3 checks passed
@pingSubhajit pingSubhajit deleted the subhajit/let-64-logic-identify-users-in-sentry-from-nextjs-service-through branch July 25, 2025 03:50
sahilverma-dev pushed a commit that referenced this pull request Aug 19, 2025
… Clerk's SDK (#166)

* feat: identify users in Sentry from Next.js service through Clerk's SDK
* fix: improve type safety in user ID handling in sentry configs
* chore: remove duplicate redundant logic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

logic: Identify users in Sentry from NextJS service through Clerk's SDK

3 participants