Skip to content

cache offline page#133

Merged
DevlinRocha merged 36 commits intomainfrom
staging
Apr 2, 2025
Merged

cache offline page#133
DevlinRocha merged 36 commits intomainfrom
staging

Conversation

@DevlinRocha
Copy link
Copy Markdown
Owner

@DevlinRocha DevlinRocha commented Mar 31, 2025

  • create offline.html file to cache and respond with service worker
  • cache offline page
  • update vite to 6.2.4
  • <DefaultNotFound /> takes in message prop

@DevlinRocha DevlinRocha added the enhancement New feature or request label Mar 31, 2025
@DevlinRocha DevlinRocha self-assigned this Mar 31, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 31, 2025

Warning

Rate limit exceeded

@DevlinRocha has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 59 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a729855 and e8664bf.

📒 Files selected for processing (1)
  • apps/frontend/public/service-worker.js (1 hunks)
📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Enhanced offline experience: The app now provides a fallback offline response during network disruptions, ensuring smoother service when connectivity is poor.
    • Improved error messaging: Blog pages and search results now display specific, user-friendly messages when content is unavailable or errors occur.

Walkthrough

This pull request addresses multiple enhancements and clarifications across the codebase. In the service worker, error handling around network fetches has been improved with a try…catch block. A resource list generation script has been simplified by removing cache array constructions. The API server’s CORS configuration now permits an additional origin. The Vite dependency version in the frontend has been updated, and several blog-related components have been modified to pass context-specific error messages to the DefaultNotFound component, which itself now accepts an optional message prop.

Changes

File(s) Change Summary
apps/frontend/public/service-worker.js Enhanced error handling in the fetch event listener by wrapping handleFetch(event.request, cache) in a try…catch block that logs network fetch errors and returns a fallback response with status 503.
apps/frontend/scripts/generate-resource-list.js Removed lines that define the resourcesToCache array and the resourceList string while retaining file write functionality.
packages/api/src/server/start-server.ts Added an extra allowed origin (https://staging.devlinrocha.pages.dev) in the production CORS configuration.
apps/frontend/package.json Updated the Vite dependency version from ^6.2.3 to ^6.2.4 in devDependencies.
apps/frontend/src/components/DefaultNotFound.tsx Modified the component to accept an optional message prop (defaulting to “page not found”) and dynamically render the message.
apps/frontend/src/routes/blog.* Updated blog routes (blog.$blogId.lazy.tsx, blog.index.lazy.tsx, blog.search.tsx) to pass specific error messages (e.g., “error loading post”, “post not found”, “error searching”, “no posts found”) to the DefaultNotFound component.

Possibly related PRs

  • service worker improvements #130: Enhances error handling in the service worker's fetch event listener, specifically by implementing a try...catch block and returning a custom Response object when network fetches fail.
  • serve cache first for offline use #125: Simplifies fetch handling in the service worker by removing the dynamic route check, related through modifications to the same service-worker.js file.
  • add blog filtering #118: Modifies the handleCache function and its invocation within the same fetch event listener, indicating a direct relationship in their modifications to the service worker's functionality.

Poem

I'm a joyful rabbit, hopping with delight,
In code-filled meadows, my heart takes flight.
With try...catch guarding every fetch in sight,
And messages that clarify errors just right,
I nibble on updates, day and night! 🐇✨


🪧 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 plan to trigger planning for file edits and PR creation.
  • @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.

@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages bot commented Mar 31, 2025

Deploying devlinrocha with  Cloudflare Pages  Cloudflare Pages

Latest commit: 74b697e
Status: ✅  Deploy successful!
Preview URL: https://582ba582.devlinrocha.pages.dev
Branch Preview URL: https://staging.devlinrocha.pages.dev

View logs

Copy link
Copy Markdown

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c9835dd and f7172b7.

📒 Files selected for processing (3)
  • apps/frontend/public/offline.html (1 hunks)
  • apps/frontend/public/service-worker.js (1 hunks)
  • apps/frontend/scripts/generate-resource-list.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha
🔇 Additional comments (3)
apps/frontend/scripts/generate-resource-list.js (1)

17-17: Good addition of offline.html to the cache list

Adding the offline page to the routesToCache array ensures it will be available when users are offline, which perfectly aligns with the PR objective.

apps/frontend/public/offline.html (1)

1-78: Nice offline page design with helpful UI elements

The offline page has a clean, minimalist design that clearly communicates the network status to users. The emoticon adds a human touch, and providing both home and refresh options gives users clear actions to take.

apps/frontend/public/service-worker.js (1)

96-106: Good implementation of offline fallback

The try-catch block effectively handles network failures and provides the offline.html page as a fallback. This creates a more robust user experience when the network is unavailable.

The error logging is thorough and will be helpful for debugging network issues, and using the cached offline page as a fallback ensures users always see something useful.

Copy link
Copy Markdown

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c9835dd and f7172b7.

📒 Files selected for processing (3)
  • apps/frontend/public/offline.html (1 hunks)
  • apps/frontend/public/service-worker.js (1 hunks)
  • apps/frontend/scripts/generate-resource-list.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha
🔇 Additional comments (1)
apps/frontend/scripts/generate-resource-list.js (1)

17-17: Offline page added to cache list

Adding /offline.html to the routesToCache array ensures that the offline page will be available when the user is offline, which is essential for the improved offline user experience.

Copy link
Copy Markdown

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

🔭 Outside diff range comments (1)
apps/frontend/public/service-worker.js (1)

43-52: 💡 Verification agent

🧩 Analysis chain

Verify offline.html is included in the cache list.

Ensure that 'offline.html' is properly included in the RESOURCE_LIST that's being cached during the service worker installation. According to the summary, it was added to the routesToCache array in generate-resource-list.js, but we should verify this.

Run the following to check if offline.html is included in the resources to be cached:


🏁 Script executed:

#!/bin/bash
# Check if offline.html is included in resource-list.js
echo "Checking if offline.html is included in RESOURCE_LIST..."
if grep -q "'/offline.html'" apps/frontend/public/resource-list.js; then
  echo "✅ '/offline.html' is included in resource-list.js"
else
  echo "❌ '/offline.html' is NOT found in resource-list.js"
fi

Length of output: 382


Action Required: Verify Offline Fallback Caching

Our automated check couldn’t locate the expected resource file at apps/frontend/public/resource-list.js, so we weren't able to verify if /offline.html is included in the cached resources. Please confirm the following:

  • Verify whether the file that defines RESOURCE_LIST is generated or located at a different path. If it’s generated (e.g., by generate-resource-list.js), ensure that the generated resource list includes /offline.html.
  • Update the service worker or caching configuration accordingly if the resource file’s location or generation logic has changed.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f7172b7 and 336753a.

📒 Files selected for processing (1)
  • apps/frontend/public/service-worker.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha
🔇 Additional comments (1)
apps/frontend/public/service-worker.js (1)

96-111: Good error handling implementation with room for improvement.

The implementation of try/catch for network requests with a fallback to the offline page is a solid approach. This ensures users will see a friendly offline message rather than a browser error.

Two suggestions that would enhance this implementation:

  1. Add request type checking before returning the offline HTML page, as returning HTML for non-HTML resources (like images, CSS, JS) could cause issues
  2. Provide a text-based fallback response if the offline page isn't found in cache
try {
    return await handleFetch(event.request, cache)
} catch (error) {
    console.error(
        `Failed to fetch from network for ${event.request.url}:`,
        error
    )

    const offline = await caches.match('/offline.html')
+   // Only return the offline page for navigation or HTML requests
+   if (event.request.mode === 'navigate' || 
+       (event.request.headers.get('accept') && 
+        event.request.headers.get('accept').includes('text/html'))) {
+       if (offline) {
            return new Response(offline, {
                status: 503,
                statusText: 'Service Unavailable',
                headers: { 'Content-Type': 'text/html' },
            })
+       }
+   }
+   // Return a plain text response for non-HTML resources or if offline page not found
+   return new Response('Network error, resource unavailable', { 
+       status: 503, 
+       statusText: 'Service Unavailable',
+       headers: { 'Content-Type': 'text/plain' }
+   })
}

Copy link
Copy Markdown

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cb8fc49 and 5a1e5b7.

📒 Files selected for processing (1)
  • apps/frontend/public/service-worker.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha

Copy link
Copy Markdown

@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

♻️ Duplicate comments (1)
apps/frontend/public/service-worker.js (1)

111-118: 🛠️ Refactor suggestion

Add null check and request type verification before serving offline page

The current implementation doesn't check if the offline page exists in the cache and serves HTML content for all request types (including images, CSS, JS), which can cause issues.

-const offlineResponse = await cache.match('/offline')
-const offlineBody = await offlineResponse.text()
-
-return new Response(offlineBody, {
-    status: 503,
-    statusText: 'Service Unavailable',
-    headers: { 'Content-Type': 'text/html' },
-})
+// Only return HTML for navigation or HTML requests
+if (event.request.mode === 'navigate' || 
+    (event.request.headers.get('accept') && 
+     event.request.headers.get('accept').includes('text/html'))) {
+    
+    const offlineResponse = await cache.match('/offline')
+    if (offlineResponse) {
+        const offlineBody = await offlineResponse.text()
+        return new Response(offlineBody, {
+            status: 503,
+            statusText: 'Service Unavailable',
+            headers: { 'Content-Type': 'text/html' },
+        })
+    }
+}
+
+// For non-HTML requests or if offline page isn't available, return a simple error response
+return new Response('Network error', { 
+    status: 503, 
+    statusText: 'Service Unavailable' 
+})

This implementation:

  1. Checks if the request is for HTML content before returning HTML
  2. Checks if the offline page exists in the cache
  3. Provides appropriate responses for different content types
🧰 Tools
🪛 GitHub Actions: CI/CD Pipeline

[error] Command failed with exit code 1: vite build && node scripts/generate-resource-list

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7339c78 and 77756b0.

📒 Files selected for processing (3)
  • apps/frontend/public/service-worker.js (3 hunks)
  • apps/frontend/scripts/generate-resource-list.js (1 hunks)
  • apps/frontend/src/assets/offline.html (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI/CD Pipeline
apps/frontend/scripts/generate-resource-list.js

[error] 30-30: Error: ENOENT: no such file or directory, open '/home/runner/work/portfolio/portfolio/apps/frontend/dist/offline.html'


[error] Command failed with exit code 1: vite build && node scripts/generate-resource-list

apps/frontend/public/service-worker.js

[error] Command failed with exit code 1: vite build && node scripts/generate-resource-list

apps/frontend/src/assets/offline.html

[error] Command failed with exit code 1: vite build && node scripts/generate-resource-list

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha

Copy link
Copy Markdown

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 77756b0 and b271099.

📒 Files selected for processing (1)
  • apps/frontend/src/assets/offline.html (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI/CD Pipeline
apps/frontend/src/assets/offline.html

[error] Command failed with exit code 1: vite build && node scripts/generate-resource-list

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha
🔇 Additional comments (1)
apps/frontend/src/assets/offline.html (1)

1-7: Standard HTML Structure Confirmed
The file correctly implements the basic HTML structure including the DOCTYPE, <html lang="en">, meta charset, viewport meta tag, and a <title> declaration. This addresses previous concerns regarding browser compatibility.

🧰 Tools
🪛 GitHub Actions: CI/CD Pipeline

[error] Command failed with exit code 1: vite build && node scripts/generate-resource-list

Copy link
Copy Markdown

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1edf61f and 8384e06.

📒 Files selected for processing (1)
  • apps/frontend/scripts/generate-resource-list.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha

Copy link
Copy Markdown

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82dd119 and 2ad5c13.

📒 Files selected for processing (1)
  • apps/frontend/public/service-worker.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha

Copy link
Copy Markdown

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2ad5c13 and 04dd410.

📒 Files selected for processing (1)
  • apps/frontend/public/service-worker.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha
🔇 Additional comments (2)
apps/frontend/public/service-worker.js (2)

48-50: Good addition of offline page caching during installation

The implementation correctly fetches and caches the offline HTML page during service worker installation. This ensures the offline experience will be available even if the user goes offline before navigating to any pages.


107-114: Enhance offline fallback logic with content type checking and null handling.

The error handling for network failures is good, but there are two issues that should be addressed:

  1. There's no null check before using offlineResponse
  2. The code returns HTML content for all request types, which can cause issues for non-HTML resources like images, CSS, and JavaScript files
try {
    return await handleFetch(event.request, cache)
} catch (error) {
    console.error(
        `Failed to fetch from network for ${event.request.url}:`,
        error
    )

    const offlineResponse = await cache.match('/offline')
-   const offlineBody = await offlineResponse.text()
-
-   return new Response(offlineBody, {
-       status: 503,
-       statusText: 'Service Unavailable',
-       headers: { 'Content-Type': 'text/html' },
-   })
+   
+   // Only return HTML for navigation or HTML requests
+   if (event.request.mode === 'navigate' || 
+       (event.request.headers.get('accept') && 
+        event.request.headers.get('accept').includes('text/html'))) {
+       
+       if (offlineResponse) {
+           const offlineBody = await offlineResponse.text()
+           return new Response(offlineBody, {
+               status: 503,
+               statusText: 'Service Unavailable',
+               headers: { 'Content-Type': 'text/html' },
+           })
+       }
+   }
+   
+   // For non-HTML requests or if offline page is not available
+   return new Response('Network error', { 
+       status: 503, 
+       statusText: 'Service Unavailable' 
+   })
}

This implementation addresses both issues by:

  1. Checking if the request is for HTML content before returning HTML
  2. Adding a null check for the offline response
  3. Providing an appropriate fallback for other content types

Copy link
Copy Markdown

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

🔭 Outside diff range comments (1)
apps/frontend/public/service-worker.js (1)

43-52: 🛠️ Refactor suggestion

Add offline.html to the precached resources

To ensure the offline page is available when needed, you should add it to the resources that are cached during service worker installation.

addEventListener('install', (event) => {
    event.waitUntil(
        (async () => {
            const cache = await getCache()
            await cache.addAll(RESOURCE_LIST)
+           // Ensure offline.html is cached
+           await cache.add('/offline.html')
        })()
    )

    skipWaiting()
})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6ab8463 and 30157f7.

📒 Files selected for processing (1)
  • apps/frontend/public/service-worker.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha

coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 2, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 2, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Apr 2, 2025
Copy link
Copy Markdown

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 41015a4 and e6794f2.

📒 Files selected for processing (1)
  • apps/frontend/public/service-worker.js (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha
🔇 Additional comments (2)
apps/frontend/public/service-worker.js (2)

99-115: Enhance the offline fallback logic for non-HTML requests and add null checks.

This code always returns HTML for any failed network request, even if the request is for static assets like images or scripts. Also, if /offline isn’t cached or is unavailable, calling offlineResponse.text() will fail. Checking if the request is HTML (e.g., via event.request.mode === 'navigate' or Accept headers) and verifying offlineResponse is not null before returning it can prevent unexpected errors.


48-50:

Details

❓ Verification inconclusive

Ensure that /offline is served as intended.

You're fetching from /offline and caching the response here. If the application intends to serve an HTML file at /offline, confirm that the server (or hosting setup) indeed responds with an offline page. Otherwise, consider referencing /offline.html or adjusting your server routes/bundler configuration to avoid 404 errors or unexpected content types.

Below is a script to locate references to “/offline” and verify any route or file references:


🏁 Script executed:

#!/bin/bash
# Searching for references to '/offline' in the repository
rg --context 5 '/offline'

Length of output: 1646


Action: Verify /offline Endpoint Configuration

We're fetching from /offline and caching its response in the service worker. Please confirm that this endpoint reliably serves the intended offline content (typically an HTML page) when there is no network connectivity. If the intended offline fallback is an HTML file (for example, named /offline.html), update the service worker code or server configuration accordingly to avoid 404 errors or content mismatches.

Copy link
Copy Markdown

@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

♻️ Duplicate comments (1)
apps/frontend/public/service-worker.js (1)

99-115: 🛠️ Refactor suggestion

Add content type checking before returning HTML response.

The current implementation returns HTML content for all request types, which can cause issues for non-HTML resources like images, CSS, and JavaScript files.

try {
    return await handleFetch(event.request, cache)
} catch (error) {
    console.error(
        `Failed to fetch from network for ${event.request.url}:`,
        error
    )

+   // Only return HTML for navigation or HTML requests
+   if (event.request.mode === 'navigate' || 
+       (event.request.headers.get('accept') && 
+        event.request.headers.get('accept').includes('text/html'))) {
        const offlineResponse = await cache.match('/offline')
        if (offlineResponse) {
            const offlineBody = await offlineResponse.text()
            return new Response(offlineBody, {
                status: 503,
                statusText: 'Service Unavailable',
                headers: { 'Content-Type': 'text/html' },
            })
        }
+       
+       // Fallback if offline page isn't in cache
+       return new Response(
+           '<main style="text-align: center; font-family: system-ui;"><h1>Network offline</h1><a href="/">Go home</a></main>',
+           {
+               status: 503,
+               statusText: 'Service Unavailable',
+               headers: { 'Content-Type': 'text/html' },
+           }
+       )
+   }
+   
+   // For non-HTML requests
+   return new Response('Network error', { 
+       status: 503, 
+       statusText: 'Service Unavailable' 
+   })
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e6794f2 and a729855.

📒 Files selected for processing (1)
  • apps/frontend/public/service-worker.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: devlinrocha

@DevlinRocha DevlinRocha force-pushed the staging branch 3 times, most recently from e8664bf to 74b697e Compare April 2, 2025 02:21
@DevlinRocha DevlinRocha changed the title create offline.html cache offline page Apr 2, 2025
@DevlinRocha DevlinRocha merged commit b7cac81 into main Apr 2, 2025
17 checks passed
@DevlinRocha DevlinRocha deleted the staging branch April 2, 2025 02:25
@DevlinRocha DevlinRocha restored the staging branch April 7, 2025 23:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant