Skip to content

Fixed Post Analytics > Newsletter tab premature redirect - #23270

Merged
cmraible merged 2 commits into
mainfrom
chris-prod-1672-post-analytics-newsletter-tab-fails-to-load-frequently
May 8, 2025
Merged

cmraible merged 2 commits into
mainfrom
chris-prod-1672-post-analytics-newsletter-tab-fails-to-load-frequently

Conversation

@cmraible

@cmraible cmraible commented May 8, 2025 •

Copy link
Copy Markdown
Collaborator

ref https://linear.app/ghost/issue/PROD-1672/post-analytics-newsletter-tab-fails-to-load-frequently

The Newsletter tab in the Post Analytics view was prematurely redirecting because the trafficAnalyticsAlpha flag hadn't been loaded yet. The redirect was occurring before the settings were loaded from the server, so unless the posts app had already been loaded and cached the settings, the Newsletter tab would redirect to the /web/ route. This /web/ route doesn't really exist, so it shows the "Loading interrupted" error.

This follows the same pattern we have in the stats app using a withFeatureFlag higher order component to put the whole route behind the flag, and critically it waits for the settings to load before redirecting.

Note: this duplicates the withFeatureFlag and useFeatureFlag hook from stats into posts. We should either merge these apps together, or most these into admin-x-framework to remove the duplication.

@coderabbitai

coderabbitai Bot commented May 8, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This change introduces a new feature flag system for the posts analytics application. A custom React hook (useFeatureFlag) and a higher-order component (withFeatureFlag) are implemented to manage feature flag checks and conditional rendering based on global settings. The Newsletter analytics route is updated to be gated by the trafficAnalyticsAlpha feature flag using the new HOC, redirecting users if the flag is disabled. The Newsletter component itself is refactored to remove direct feature flag checks, delegating that responsibility to the new system. The global data provider is also updated to track both config and settings loading and error states.

Possibly related PRs

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.

apps/posts/src/routes.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "/apps/posts".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in "apps/posts/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

apps/posts/src/hooks/withFeatureFlag.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "/apps/posts".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in "apps/posts/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

apps/posts/src/hooks/useFeatureFlag.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "/apps/posts".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in "apps/posts/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

  • 2 others

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ 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.

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

@cmraible
cmraible marked this pull request as ready for review May 8, 2025 22:32

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/posts/src/hooks/useFeatureFlag.tsx (1)

17-18: Consider adding error handling for JSON parsing

The JSON parsing could potentially throw an error if the labs setting contains malformed JSON. Consider adding a try-catch block to handle this gracefully.

- const labsJSON = getSettingValue<string>(settings, 'labs') || '{}';
- const labs = JSON.parse(labsJSON);
+ const labsJSON = getSettingValue<string>(settings, 'labs') || '{}';
+ let labs = {};
+ try {
+   labs = JSON.parse(labsJSON);
+ } catch (e) {
+   console.error('Failed to parse labs settings:', e);
+ }
apps/posts/src/hooks/withFeatureFlag.tsx (1)

31-42: Consider enhancing the loading placeholder.

The loading state is currently an empty div with a comment. Consider adding a more meaningful loading indicator or skeleton UI to improve user experience during loading.

-                        <div>{/* Loading placeholder */}</div>
+                        <div aria-label="Loading content" className="skeleton-loading">
+                            {/* Skeleton UI elements can go here */}
+                        </div>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3fddc63 and 695ddeb.

📒 Files selected for processing (5)
  • apps/posts/src/hooks/useFeatureFlag.tsx (1 hunks)
  • apps/posts/src/hooks/withFeatureFlag.tsx (1 hunks)
  • apps/posts/src/providers/GlobalDataProvider.tsx (1 hunks)
  • apps/posts/src/routes.tsx (2 hunks)
  • apps/posts/src/views/PostAnalytics/Newsletter.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/posts/src/hooks/useFeatureFlag.tsx (1)
apps/posts/src/providers/GlobalDataProvider.tsx (1)
  • useGlobalData (20-26)
apps/posts/src/hooks/withFeatureFlag.tsx (1)
apps/posts/src/hooks/useFeatureFlag.tsx (1)
  • useFeatureFlag (13-47)
🔇 Additional comments (9)
apps/posts/src/providers/GlobalDataProvider.tsx (1)

36-38: Good approach to centralized loading and error handling!

This is a solid implementation that properly tracks loading and error states across both config and settings requests. It ensures that the component waits for all data to be available before rendering, preventing premature actions that depend on settings.

apps/posts/src/views/PostAnalytics/Newsletter.tsx (1)

72-72: Clean simplification of loading state logic

Simplifying the loading state to only depend on newsletter stats loading is appropriate now that the feature flag logic has been moved to the HOC.

apps/posts/src/routes.tsx (2)

10-11: Good implementation of feature flag protection at route level

Wrapping the Newsletter component with the feature flag HOC at the route level is a clean approach that properly separates concerns and ensures the component isn't rendered until the feature flag is checked.


37-37: LGTM - Properly uses the protected component

The route now correctly uses the feature flag-protected component instead of the raw Newsletter component.

apps/posts/src/hooks/useFeatureFlag.tsx (1)

13-47: Well-implemented feature flag hook with proper loading handling

This hook correctly handles the loading state to prevent premature redirects, which addresses the core issue described in the PR. The implementation effectively guards against the race condition where redirection happens before settings are loaded.

apps/posts/src/hooks/withFeatureFlag.tsx (4)

7-15: Well-documented Higher-Order Component.

The JSDoc comments are thorough and clearly explain the purpose and parameters of the HOC, which will help other developers understand how to use it.


16-21: Good use of TypeScript generics for type safety.

The generic type parameter P extends object ensures that props are properly typed and passed through to the wrapped component, maintaining type safety throughout.


22-28: Clean handling of redirect state.

The code appropriately checks for the redirect case first and returns early if needed, following good control flow practices.


48-49: Good practice setting displayName for debugging.

Setting a descriptive display name with fallbacks helps with debugging and component identification in React DevTools.

@cmraible
cmraible merged commit 26de9ed into main May 8, 2025
@cmraible
cmraible deleted the chris-prod-1672-post-analytics-newsletter-tab-fails-to-load-frequently branch May 8, 2025 22:37
cmraible added a commit that referenced this pull request Aug 20, 2026
no refs

## Evidence that the component is unused

`PostAnalyticsView` is not exported by the private Admin package, and
repository-wide searches for both its symbol and module path find no
importer. Admin-only Knip reported
`apps/admin/src/posts/analytics/components/post-analytics-view.tsx` as
an unused file before this removal and stopped reporting it afterward.
The Admin build uses explicit routes and entry points; no dynamic import
or glob references this path.

## History and intentionality

Documented facts:

-
ad52284
introduced the component as the loading/empty/content wrapper in the
first React post-analytics skeleton.
#22978 explains that the work
began a better breakdown of post statistics, initially focused on web
analytics for one post.
-
54d993b
replaced that static wrapper in the main page with real post and traffic
data. #22986 says this made the
previously static skeleton usable for beta users.
-
26de9ed
later reused the component only as the loading screen for a duplicated
`withFeatureFlag` wrapper. #23270
documents that the wrapper prevented the Newsletter tab from redirecting
before the alpha setting had loaded, and explicitly called the
duplication temporary.
- #23029 documents the rollout
model: `trafficAnalytics` selected beta users, while
`trafficAnalyticsAlpha` selected features still under development for
that beta.
-
f0a33b8
intentionally moved Newsletter analytics out of alpha. Its diff replaced
the protected route with the direct `Newsletter` route and made the
sidebar links unconditional;
#23294 states that purpose
directly. Production therefore stopped reaching the wrapper, and
consequently `PostAnalyticsView`, on May 12, 2025. Given the documented
flag semantics, this was an intentional promotion to the analytics beta
rather than an accidental bypass.
-
fb0790b
later restored the alpha flag for other design work but did not restore
Newsletter's route guard, corroborating that Newsletter's promotion was
deliberate.
-
566f8a9
removed the now-unreachable wrapper and its tests.
#29686 identifies those files as
duplicated dead code with no live importers. That deletion removed the
component's last source or test importer on July 30, 2026.

Inference: leaving `PostAnalyticsView` behind in that last cleanup was
an incomplete leaf cleanup. No historical source explicitly describes
the omission, but the dead-code PR's stated intent, the current
zero-reference result, and Knip's independent unused-file report support
that conclusion.

## Removal

Deleted the 33-line orphaned component. It had no dedicated tests,
export, dependency, configuration, or documentation to remove. Its
`EmptyStatView` and `PostAnalyticsContent` dependencies remain used by
live analytics screens.

## Verification

- `pnpm exec knip --workspace @tryghost/admin --include files --reporter
compact --no-progress` (the removed file is absent; four pre-existing
acceptance setup/config entries remain)
- `pnpm --dir apps/admin lint`
- `pnpm --dir apps/admin typecheck`
- `pnpm --dir apps/admin test:unit` (135 files, 1,604 tests)
- `pnpm nx run @tryghost/admin:build`
- `pnpm nx run-many -t test --exclude @tryghost/e2e --exclude
ghost-admin --exclude @tryghost/koenig-lexical` (35 projects, including
8,000 Ghost tests)

`pnpm check` completed repository-wide lint and documentation checks,
but its aggregate test phase could not run Koenig Lexical's browser
suite in this environment: Chromium was denied Mach port registration
and the configured Firefox executable is absent. The broader test run
above excludes only that environment-blocked package and passed.
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