Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ✨ add amplitude domain proxy #4024

Conversation

DavideSegullo
Copy link
Collaborator

@DavideSegullo DavideSegullo commented Dec 18, 2024

What is the purpose of the change:

Right now due to uBlock or stuffs like that, our request to amplitude are blocked for some users, this create a lot of missing data in our metrics. This PR should address this issue by using a domain proxy!

Linear Task

https://linear.app/osmosis/issue/FE-1233/amplitude-or-using-proxy-to-redirect-event-logs-to-amplitude

Brief Changelog

Testing and Verifying

Copy link

vercel bot commented Dec 18, 2024

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

Name Status Preview Comments Updated (UTC)
osmosis-frontend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 18, 2024 8:14pm
4 Skipped Deployments
Name Status Preview Comments Updated (UTC)
osmosis-frontend-datadog ⬜️ Ignored (Inspect) Visit Preview Dec 18, 2024 8:14pm
osmosis-frontend-dev ⬜️ Ignored (Inspect) Visit Preview Dec 18, 2024 8:14pm
osmosis-frontend-edgenet ⬜️ Ignored (Inspect) Dec 18, 2024 8:14pm
osmosis-testnet ⬜️ Ignored (Inspect) Visit Preview Dec 18, 2024 8:14pm

Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/web/hooks/use-amplitude-analytics.ts

Oops! Something went wrong! :(

ESLint: 8.50.0

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/packages/web/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

The pull request modifies the use-amplitude-analytics.ts hook to enhance Amplitude analytics initialization. The key change involves updating the amplitudeInit function call to include an optional serverUrl parameter, which is populated from the NEXT_PUBLIC_AMPLITUDE_SERVER_URL environment variable. This modification allows for more flexible configuration of the Amplitude analytics server URL during initialization, while maintaining the existing hook's core functionality and structure.

Changes

File Change Summary
packages/web/hooks/use-amplitude-analytics.ts Updated amplitudeInit function call to include serverUrl option from environment variable

Possibly related PRs

Suggested reviewers

  • fabryscript
  • JoseRFelix

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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
Contributor

@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: 2

🧹 Nitpick comments (2)
packages/web/hooks/use-amplitude-analytics.ts (2)

Line range hint 1-90: Add documentation for the proxy configuration

The code would benefit from documentation explaining the proxy setup and configuration requirements.

Add a comment block above the useAmplitudeAnalytics hook explaining:

  • The purpose of the proxy
  • Required environment variables
  • Configuration instructions
+/**
+ * Amplitude analytics hook with proxy support to prevent ad-blockers from blocking analytics.
+ * 
+ * Configuration:
+ * - NEXT_PUBLIC_AMPLITUDE_API_KEY: Your Amplitude API key
+ * - NEXT_PUBLIC_AMPLITUDE_SERVER_URL: URL of your proxy server that forwards requests to Amplitude
+ *
+ * @example
+ * ```
+ * export function MyComponent() {
+ *   useAmplitudeAnalytics({ init: true });
+ *   // ...
+ * }
+ * ```
+ */
 export function useAmplitudeAnalytics({

62-64: Consider adding debug logging for proxy configuration

Since the DEBUG flag is already implemented, extend it to include proxy-related information.

 if (init) {
   if (process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY !== undefined) {
+    if (DEBUG) {
+      console.info('Initializing Amplitude with proxy:', {
+        apiKey: process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY,
+        proxyUrl: process.env.NEXT_PUBLIC_AMPLITUDE_SERVER_URL
+      });
+    }
     amplitudeInit(process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY, undefined, {
       serverUrl: process.env.NEXT_PUBLIC_AMPLITUDE_SERVER_URL,
     });
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4d338e4 and ee664a6.

📒 Files selected for processing (1)
  • packages/web/hooks/use-amplitude-analytics.ts (1 hunks)
🔇 Additional comments (1)
packages/web/hooks/use-amplitude-analytics.ts (1)

62-64: Verify the proxy URL configuration in the deployment environment

The implementation correctly adds the proxy server URL configuration. However, ensure that:

  1. The proxy server URL is properly configured in all deployment environments
  2. The URL is properly sanitized and validated before use

Consider implementing URL validation before passing it to amplitudeInit to prevent potential security issues.

Comment on lines +62 to +64
amplitudeInit(process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY, undefined, {
serverUrl: process.env.NEXT_PUBLIC_AMPLITUDE_SERVER_URL,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for proxy server failures

The current implementation doesn't handle scenarios where the proxy server might be unavailable or return errors.

Consider adding a fallback mechanism:

 amplitudeInit(process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY, undefined, {
   serverUrl: process.env.NEXT_PUBLIC_AMPLITUDE_SERVER_URL,
+  transport: {
+    retry: {
+      maxRetries: 3,
+      backoffFactor: 2
+    },
+    onError: (error) => {
+      console.error('Amplitude proxy error:', error);
+      // Optionally fall back to direct connection
+    }
+  }
 });

Committable suggestion skipped: line range outside the PR's diff.


💡 Codebase verification

Server-side proxy implementation is missing

Based on the verification results, while the client-side is configured to use a proxy server URL through NEXT_PUBLIC_AMPLITUDE_SERVER_URL, there is no corresponding server-side implementation found in the codebase:

  • No API routes handling Amplitude proxy requests
  • No proxy configuration in Next.js config
  • No server middleware implementation

The proxy server implementation needs to be added to handle:

  1. Request forwarding to Amplitude's servers
  2. CORS and security headers
  3. Rate limiting
  4. Error handling
🔗 Analysis chain

Verify the proxy server implementation

The changes only show the client-side configuration for the proxy. Ensure that the corresponding proxy server implementation exists and handles:

  1. Request forwarding to Amplitude
  2. CORS configuration
  3. Rate limiting
  4. Error handling
  5. Security headers

Let's try another search strategy to find the server-side implementation.


Let's try one more time with corrected file type flags:


Let's check one final time for API routes with a corrected path:


Let's check the Next.js configuration for any proxy setup:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Look for proxy server implementation
echo "Checking for proxy server implementation..."
fd -e ts -e js -e tsx -e jsx --full-path ".*proxy.*amplitude.*"

# Check for deployment configurations
echo "Checking for deployment configurations..."
fd -e yaml -e yml --full-path ".*deploy.*"

Length of output: 300


Script:

#!/bin/bash
# Search for Amplitude-related files and their content
echo "Searching for Amplitude-related files..."
rg -l "amplitude" --type ts --type js --type tsx --type jsx

# Show content of found files to analyze the implementation
echo -e "\nSearching for server-related Amplitude code..."
rg "amplitude.*server" -i --type ts --type js --type tsx --type jsx -B 2 -A 2

Length of output: 395


Script:

#!/bin/bash
# Search for Amplitude-related files
echo "Searching for Amplitude-related files..."
rg -l "amplitude"

# Look for server implementations or configurations
echo -e "\nChecking for server implementations..."
rg -i "server.*amplitude|amplitude.*server" -A 3 -B 3

# Check for API routes that might handle proxying
echo -e "\nChecking for API routes..."
fd -e ts -e js "api" "pages"

Length of output: 1867


Script:

#!/bin/bash
# Check for API routes in the web package
echo "Checking for API routes in web package..."
fd -e ts -e js "api" "packages/web/pages"

# Look for Next.js configuration that might contain proxy settings
echo -e "\nChecking Next.js configuration..."
fd -e js -e ts "next.config" "packages/web"

# Check environment variables related to Amplitude
echo -e "\nChecking environment variable files..."
fd -g "*.env*" "packages/web"

Length of output: 408


Script:

#!/bin/bash
# Check Next.js config content for proxy settings
echo "Checking Next.js config content..."
cat packages/web/next.config.js

# Look for any rewrites or proxy configurations in the codebase
echo -e "\nSearching for proxy or rewrite configurations..."
rg -i "rewrites|proxy" packages/web/next.config.js -A 5 -B 5

Length of output: 3588

@DavideSegullo DavideSegullo merged commit 7b03c95 into stage Dec 19, 2024
34 of 36 checks passed
@DavideSegullo DavideSegullo deleted the davidesegullo/fe-1233-amplitude-using-proxy-to-redirect-event-logs-to-amplitude branch December 19, 2024 15:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants