Skip to content

Normalize backend protocol for web vitals reporting#144

Merged
shayancoin merged 1 commit intomainfrom
codex/add-web-vitals-reporting-to-backend
Oct 18, 2025
Merged

Normalize backend protocol for web vitals reporting#144
shayancoin merged 1 commit intomainfrom
codex/add-web-vitals-reporting-to-backend

Conversation

@shayancoin
Copy link
Owner

@shayancoin shayancoin commented Oct 16, 2025

Summary

  • trim and normalize the configured backend protocol so the Web Vitals reporter builds a valid URL when using the backend configuration

Testing

  • not run (not requested)

https://chatgpt.com/codex/tasks/task_e_68f1571576ac8330b06da1c887db0274

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced protocol handling for backend connections to ensure more reliable and robust connectivity initialization.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 16, 2025

Walkthrough

A normalizeProtocol function is introduced to sanitize protocol strings by handling undefined or empty inputs and ensuring trailing colons. The backend protocol configuration now applies this normalization function before using the environment variable value, improving input robustness.

Changes

Cohort / File(s) Summary
Protocol normalization function
frontend/src/app/reportWebVitals.ts
Adds normalizeProtocol() utility to sanitize protocol strings; refactors endpoint building to normalize NEXT_PUBLIC_BACKEND_PROTOCOL before use, preserving fallback chain (window.location.protocol → 'http:')

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 A protocol walks in, all messy and worn,
We trim its edges and give it form—
A colon appended, undefined cast away,
Now endpoints are clean and ready to play! 🎯

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description is missing a critical required section from the template: the "# PR Type" field is not included. Instead of following the template structure with "# PR Type", "# Short Description", and "# Tests Added", the description uses "## Summary" and "## Testing" with different heading levels. While the description does communicate the essential information (what changed, why it matters, and testing status), it fails to conform to the required template structure and section headings specified in the repository's guidelines. Please update the pull request description to follow the required template format. Add the "# PR Type" section at the top and specify whether this is a Feature, Fix, Documentation, or Other change. Adjust the section headings to match the template (using "# " instead of "## " and using "Short Description" and "Tests Added" instead of "Summary" and "Testing"). The content itself is informative, so only the structure and headings need adjustment.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title "Normalize backend protocol for web vitals reporting" directly and clearly reflects the main change in the changeset. It specifically identifies what is being normalized (backend protocol) and the context where it applies (web vitals reporting), which aligns with the introduction of the normalizeProtocol() function in reportWebVitals.ts and its integration with the Web Vitals reporting setup. The title is concise, uses clear language without noise or vague terms, and a teammate scanning the git history would immediately understand the primary change being made.
✨ Finishing touches
  • 📝 Docstrings were successfully generated.
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-web-vitals-reporting-to-backend

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting

Comment on lines +6 to +17
function normalizeProtocol(protocol: string | undefined): string | undefined {
if (protocol === undefined) {
return undefined;
}

const trimmedProtocol = protocol.trim();

if (!trimmedProtocol) {
return undefined;
}

return trimmedProtocol.endsWith(':') ? trimmedProtocol : `${trimmedProtocol}:`;

Choose a reason for hiding this comment

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

P1 Badge Strip slashes when normalizing backend protocol

The new normalizeProtocol helper appends a colon without first removing any trailing slashes. When NEXT_PUBLIC_BACKEND_PROTOCOL is set to the common value 'https://' (or 'http://'), the function now returns 'https://:', so buildEndpoint emits URLs like https://://host/.... fetch rejects these with TypeError: Failed to parse URL, which prevents web‑vitals from being reported. Before this change the same configuration produced 'https:////host', which browsers normalize to a valid https://host/... request, so this is a regression. Consider trimming any trailing slashes before ensuring the colon.

Useful? React with 👍 / 👎.

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: 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 2e404f3 and 52227ae.

📒 Files selected for processing (1)
  • frontend/src/app/reportWebVitals.ts (1 hunks)
🔇 Additional comments (1)
frontend/src/app/reportWebVitals.ts (1)

25-26: LGTM! Protocol fallback chain is sound.

The normalization is correctly applied to the environment variable, and the fallback to window.location.protocol or 'http:' handles cases where the normalized value is undefined.

Comment on lines +6 to +18
function normalizeProtocol(protocol: string | undefined): string | undefined {
if (protocol === undefined) {
return undefined;
}

const trimmedProtocol = protocol.trim();

if (!trimmedProtocol) {
return undefined;
}

return trimmedProtocol.endsWith(':') ? trimmedProtocol : `${trimmedProtocol}:`;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Add test coverage for the normalization function.

The PR notes indicate testing was not run. Given that normalizeProtocol handles various edge cases (undefined, empty strings, whitespace, trailing colons, etc.), unit tests would help prevent regressions and document expected behavior.

Do you want me to generate test cases for normalizeProtocol covering scenarios like:

  • undefinedundefined
  • ""undefined
  • " "undefined
  • "http""http:"
  • "https:""https:"
  • "http://""http:"
  • " https ""https:"

🧹 Nitpick | 🔵 Trivial

Consider validating the protocol value.

While the normalization handles basic formatting, it doesn't validate that the protocol is one of the expected values (http or https). An invalid protocol value could lead to failed requests or unexpected behavior.

Consider adding validation:

 function normalizeProtocol(protocol: string | undefined): string | undefined {
   if (protocol === undefined) {
     return undefined;
   }
 
   const trimmedProtocol = protocol.trim();
 
   if (!trimmedProtocol) {
     return undefined;
   }
 
   const withoutSlashes = trimmedProtocol.replace(/\/+$/, '');
-  return withoutSlashes.endsWith(':') ? withoutSlashes : `${withoutSlashes}:`;
+  const normalized = withoutSlashes.endsWith(':') ? withoutSlashes : `${withoutSlashes}:`;
+  
+  // Validate against expected protocols
+  const baseProtocol = normalized.replace(/:$/, '').toLowerCase();
+  if (!['http', 'https', 'ws', 'wss'].includes(baseProtocol)) {
+    console.warn(`Invalid protocol "${protocol}", expected http/https/ws/wss`);
+    return undefined;
+  }
+  
+  return normalized;
 }

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

🤖 Prompt for AI Agents
In frontend/src/app/reportWebVitals.ts around lines 6 to 18, the
normalizeProtocol function trims and appends a colon but does not validate that
the protocol is an allowed value; add validation after trimming to allow only
"http" or "https" (case-insensitive) and return undefined for anything else.
Implement by normalizing case (e.g., toLowerCase()), check against a small
whitelist ["http","https"], and return the trimmed protocol with a trailing
colon only when it matches; otherwise return undefined.

⚠️ Potential issue | 🟠 Major

Handle protocol strings containing slashes.

The normalization doesn't account for common misconfigurations like "http://" or "https://". If NEXT_PUBLIC_BACKEND_PROTOCOL is set to "http://", the function returns "http://:", which produces an invalid URL at line 32: "http://:hostname...".

Apply this diff to strip trailing slashes before adding the colon:

 function normalizeProtocol(protocol: string | undefined): string | undefined {
   if (protocol === undefined) {
     return undefined;
   }
 
   const trimmedProtocol = protocol.trim();
 
   if (!trimmedProtocol) {
     return undefined;
   }
 
-  return trimmedProtocol.endsWith(':') ? trimmedProtocol : `${trimmedProtocol}:`;
+  const withoutSlashes = trimmedProtocol.replace(/\/+$/, '');
+  return withoutSlashes.endsWith(':') ? withoutSlashes : `${withoutSlashes}:`;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function normalizeProtocol(protocol: string | undefined): string | undefined {
if (protocol === undefined) {
return undefined;
}
const trimmedProtocol = protocol.trim();
if (!trimmedProtocol) {
return undefined;
}
return trimmedProtocol.endsWith(':') ? trimmedProtocol : `${trimmedProtocol}:`;
}
function normalizeProtocol(protocol: string | undefined): string | undefined {
if (protocol === undefined) {
return undefined;
}
const trimmedProtocol = protocol.trim();
if (!trimmedProtocol) {
return undefined;
}
const withoutSlashes = trimmedProtocol.replace(/\/+$/, '');
return withoutSlashes.endsWith(':') ? withoutSlashes : `${withoutSlashes}:`;
}
🤖 Prompt for AI Agents
In frontend/src/app/reportWebVitals.ts around lines 6 to 18, normalizeProtocol
currently trims the input but does not remove trailing slashes, so values like
"http://" become "http://:" and produce invalid URLs; update the function to
remove any trailing slashes after trimming (e.g. strip all trailing '/'
characters), then treat an empty result as undefined and finally ensure it ends
with a single ':' (add one if missing) before returning.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 18, 2025

Note

Docstrings generation - SUCCESS
Generated docstrings for this pull request at #289

@shayancoin shayancoin merged commit f68398d into main Oct 18, 2025
2 of 7 checks passed
coderabbitai bot added a commit that referenced this pull request Oct 18, 2025
Docstrings generation was requested by @shayancoin.

* #144 (comment)

The following files were modified:

* `frontend/src/app/reportWebVitals.ts`
shayancoin pushed a commit that referenced this pull request Oct 18, 2025
Docstrings generation was requested by @shayancoin.

* #144 (comment)

The following files were modified:

* `frontend/src/app/reportWebVitals.ts`

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant