Skip to content

fix: attempt deeplink fix for pwa#754

Merged
kushagrasarathe merged 1 commit intopeanut-wallet-devfrom
fix/deeplink
Mar 20, 2025
Merged

fix: attempt deeplink fix for pwa#754
kushagrasarathe merged 1 commit intopeanut-wallet-devfrom
fix/deeplink

Conversation

@kushagrasarathe
Copy link
Copy Markdown
Contributor

@kushagrasarathe kushagrasarathe commented Mar 20, 2025

contributes to TASK-9537

Summary by CodeRabbit

  • New Features

    • Enhanced security and functionality with updated settings that improve service worker support and page embedding restrictions.
    • Improved mobile and progressive web app integration through enriched metadata, manifest updates, and optimized deep linking for smoother navigation.
  • Refactor

    • Streamlined the payment page layout to deliver a more consistent and user-friendly experience.

@vercel
Copy link
Copy Markdown

vercel bot commented Mar 20, 2025

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

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 20, 2025 4:57pm

@notion-workspace
Copy link
Copy Markdown

Fix deeplink

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 20, 2025

Walkthrough

The pull request introduces modifications across several parts of the application. In the Next.js configuration, new security headers are added. The PaymentPage component’s rendering logic has been simplified for consistency. The apple-app-site-association API now explicitly sets the Content-Type header, and the manifest file is extended with additional properties for deep linking. Additional metadata is provided for mobile web app configurations, and a new service worker fetch event listener has been implemented to handle PWA deep linking by focusing or opening the appropriate window.

Changes

File(s) Summary
next.config.js Added Service-Worker-Allowed (value '/') and X-Frame-Options (value 'DENY') headers to enhance security and control service worker and iframe behavior.
src/app/[...recipient]/page.tsx Simplified conditional rendering for the CONFIRM view by removing an extra <div> and unifying the main <div> to always use self-center for layout consistency.
src/app/api/apple-app-site-association/route.ts Reordered import statements and added a headers object with Content-Type: application/json in the GET response to ensure proper content type interpretation.
src/app/manifest.ts Introduced the ExtendedManifest interface, updated the return type of the manifest function, and adjusted the handling of the scope property for flexibility.
src/app/metadata.ts Added mobile web app metadata including an other object and new properties (applicationName, appleWebApp) to support enhanced mobile integration for the app.
src/app/sw.ts Implemented a new fetch event listener to handle navigation requests for PWA deep linking by focusing an active window or opening a new one, with a fallback to default fetch.

Sequence Diagram(s)

sequenceDiagram
    participant Browser as Browser
    participant SW as Service Worker
    participant Client as PWA Window

    Browser->>SW: Navigation request (fetch event)
    SW->>SW: Check if event.mode === "navigate"
    SW->>SW: Invoke self.clients.matchAll()
    alt Active PWA window(s) exist
        SW->>Client: Focus window and navigate to requested URL
    else No active window found
        SW->>Browser: Open new window with the requested URL
    end
    SW-->>Browser: Return response (or fallback to default fetch on error)
Loading

Possibly related PRs

  • dev main sync #596: Relates to security header adjustments addressing iframe scenarios similar to the new headers added in next.config.js.

Suggested reviewers

  • jjramirezn

Poem

I'm a rabbit hopping with glee,
Skipping through changes, wild and free.
Headers guard like a carrot moon,
Payment flows groove to a rhythmic tune.
PWA windows open in a dance so bright,
CodeRabbit cheers—coding day and night!
🥕🐰 Happy hops and bug-free delight!


📜 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 27d2fce and b395883.

📒 Files selected for processing (6)
  • next.config.js (1 hunks)
  • src/app/[...recipient]/page.tsx (1 hunks)
  • src/app/api/apple-app-site-association/route.ts (1 hunks)
  • src/app/manifest.ts (2 hunks)
  • src/app/metadata.ts (1 hunks)
  • src/app/sw.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/app/api/apple-app-site-association/route.ts (4)
src/app/api/assetLinks/route.ts (2) (2)
  • dynamic (4-4)
  • GET (7-13)
src/app/api/bridge/liquidation-address/get-all/route.ts (2) (2)
  • dynamic (4-4)
  • GET (7-50)
src/app/api/peanut/user/fetch-user/route.ts (2) (2)
  • dynamic (6-6)
  • GET (8-49)
src/utils/sentry.utils.ts (1) (1)
  • fetchWithSentry (11-87)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (11)
src/app/api/apple-app-site-association/route.ts (2)

3-5: Adjusted imports and dynamic export declaration.

The imports for NextRequest and NextResponse have been reordered, and the dynamic export has been moved. This maintains the same functionality while improving code organization.


10-16: Improved API response with explicit Content-Type header.

Adding the Content-Type: application/json header ensures proper handling of the Apple App Site Association file by Apple's servers. This is essential for Universal Links to work correctly in iOS environments and aligns with Apple's requirements for handling deep links.

next.config.js (1)

142-151: Added critical headers for PWA deep linking and security.

These security headers are essential for the PWA deep linking functionality:

  1. Service-Worker-Allowed: / - Enables the service worker to handle all routes in the application, which is necessary for the deep linking implementation in sw.ts
  2. X-Frame-Options: DENY - Prevents clickjacking attacks by ensuring the PWA cannot be embedded in iframes

Both headers improve the security posture while enabling the required functionality for deep linking to work properly.

src/app/[...recipient]/page.tsx (1)

153-158: Simplified component structure and standardized layout.

The layout has been standardized to consistently use self-center for alignment, and the ConfirmPaymentView is now rendered directly without the additional wrapping div. This makes the code more consistent and easier to maintain while ensuring a uniform layout across different view states.

src/app/sw.ts (1)

58-89:

Details

✅ Verification successful

Implemented PWA deep linking handler in service worker.

This fetch event listener is the core of the deep linking fix. When a user navigates to a URL (like through an external link), it:

  1. Identifies navigation requests
  2. Checks if the PWA is already open in a window
  3. If open, focuses that window and navigates to the requested URL
  4. If not open, opens a new window with the URL
  5. Has a fallback to standard fetch behavior if any errors occur

This implementation follows best practices for PWA deep linking by ensuring a smooth user experience when accessing the app through external links.


🌐 Web query:

What are the best practices for implementing PWA deep linking with service workers?

💡 Result:

To implement deep linking in Progressive Web Apps (PWAs) with service workers effectively, follow these best practices derived from industry standards and technical guidelines:

1. Use Unique, Shareable URLs

Ensure every app section has a distinct URL (e.g., https://example.com/products/123). This supports deep linking by allowing users to share, bookmark, or navigate directly to specific content. Service workers should cache these URLs to enable offline access to deep-linked pages[2][6][13].


2. Leverage Service Workers for Offline Support

  • Cache Critical Routes: Precache static assets (HTML, CSS, JS) and dynamic content associated with deep-linked URLs during service worker installation[4][8][18].
  • Fallback Strategies: Serve custom offline pages or cached content when network requests fail, maintaining functionality for previously visited deep-linked paths[2][13][17].
// Example: Cache-first strategy for deep-linked routes
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then((response) => response || fetch(event.request))
  );
});

3. Implement Platform-Specific Handling

  • Android: Use the default web-based deep linking, which opens installed PWAs for URLs within their scope[9][13].
  • iOS: Fallback to Safari since iOS lacks native PWA deep linking[9]. Consider prompting users to install the PWA or redirecting to web content.
  • Desktop: Handle links via push notifications or OS integrations (e.g., Windows Widgets)[9][13].

4. Enable Cross-Platform Compatibility

  • Custom URI Schemes: For non-web contexts (e.g., QR codes, SMS), use prefixes like myapp://product/123. Service workers can intercept these if the PWA is registered as a protocol handler[1][5][9].
  • Deferred Deep Linking: Redirect users to app stores if the PWA isn’t installed, then launch the content post-installation[3][5].

5. Integrate with the OS and Browsers

  • Web App Manifest: Declare start_url and scope to define installable behavior and URL boundaries[2][10][15].
  • Link Preloading: Use <link rel="preconnect"> or <link rel="dns-prefetch"> to accelerate deep-link resolution in browsers[7][16].
// Manifest example
{
  "start_url": "/",
  "scope": "/",
  "display": "standalone"
}

6. Optimize for SEO and Discoverability

  • Ensure deep-linked pages are crawlable by search engines using semantic HTML and metadata[2][6][13].
  • Use server-side rendering (SSR) or dynamic rendering for JavaScript-heavy content to improve indexing[13][18].

7. Test Across Scenarios

  • Validate offline behavior using tools like Lighthouse and DevTools’ Network Throttling[8][10][17].
  • Verify deep-link functionality on multiple platforms (iOS/Android/desktop) and browsers (Chrome, Safari, Edge)[2][9][13].

By combining service worker caching, platform-aware routing, and standards-compliant URL structures, PWAs can deliver seamless deep-linking experiences while maintaining offline capabilities and cross-device consistency.

Citations:


Approved: PWA Deep Linking Handler Conforms to Best Practices

  • The service worker correctly intercepts navigation requests and uses event.request.mode to target navigations.
  • It effectively checks for an existing PWA window, focusing and navigating it if present, or opens a new window when none exists.
  • The fallback to the default fetch ensures that, in case of errors, the request continues as normal.
  • This approach aligns with industry guidelines for seamless deep linking. In the future, you might consider incorporating caching strategies for offline support of deep-linked content if your requirements evolve.
src/app/manifest.ts (3)

3-7: Good addition of extended manifest interface for PWA deep linking

The extension of the manifest type to include capture_links and handle_links properties is a good approach for implementing PWA deep linking capabilities.


9-9: Appropriate update to the function return type

Updating the return type to match the extended interface provides proper type safety.


24-24: Scope property added correctly

Adding the scope property with value '/' is correct for handling deep links across your entire application.

src/app/metadata.ts (3)

36-42: Good addition of mobile web app properties

Adding these mobile web app properties enhances the PWA experience, particularly for iOS users. The properties are correctly configured to enable standalone mode and set appropriate app title and status bar styling.


43-49: Well-configured Apple web app properties

The applicationName and appleWebApp configuration is appropriate for iOS PWA integration. The capable: true setting is essential for standalone mode, and the status bar style and startup image are properly defined.


36-49:

Details

❓ Verification inconclusive

Consider additional verification for PWA deep linking

The metadata changes look good, but it's important to verify that they work properly with the service worker implementation for deep linking mentioned in the summary.

Make sure to test these scenarios:

  1. Opening the app from a deep link when the PWA is already installed
  2. Opening a deep link when the PWA is running in the background
  3. Opening a deep link from a different app

🏁 Script executed:

#!/bin/bash
# Check for service worker implementation that handles deep linking
rg -A 5 "fetch|navigation" src/app/sw.ts

Length of output: 713


PWA Deep Linking and Metadata Verification

The metadata updates in src/app/metadata.ts look correct, and the service worker code in src/app/sw.ts confirms that navigation requests for deep linking are being handled. However, please manually test that deep linking works as expected in these scenarios:

  • Opening the app from a deep link when the PWA is already installed.
  • Opening a deep link when the PWA is running in the background.
  • Opening a deep link from a different app.
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • 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 generate docstrings to generate docstrings 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.

@kushagrasarathe kushagrasarathe merged commit 2219b7c into peanut-wallet-dev Mar 20, 2025
5 checks passed
@Hugo0 Hugo0 deleted the fix/deeplink branch July 3, 2025 18:24
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.

1 participant