Skip to content

Conversation

@South-IN
Copy link
Contributor

✨ Codu Pull Request 💻

Fixes #1066

Pull Request details

  • Implemented a new Open Graph (OG) Image Component for shared articles.
  • Added a feature flag using PostHog to toggle the OG Image Component.
  • Created a posthog.ts file to create a posthog client for the server side.

Any Breaking changes

None

Associated Screenshots

New image component :
image

Feature flag demo :

og-image-feature-flag.mp4

@South-IN South-IN requested a review from a team as a code owner October 11, 2024 11:22
@vercel
Copy link

vercel bot commented Oct 11, 2024

@South-IN is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

The changes in this pull request enhance the Open Graph image generation functionality within the app/og/route.tsx file by integrating a feature flag check and logging events with the PostHogClient. A new function, getData, is introduced to manage feature flag retrieval. Additionally, a new file, app/posthog.ts, is created to initialize the PostHog client, which is used for event tracking. The image generation logic now produces different designs based on the feature flag's state, improving the visual output.

Changes

File Change Summary
app/og/route.tsx Enhanced GET function to include feature flag checks for Open Graph image generation. Added event logging with PostHogClient. Introduced async function getData().
app/posthog.ts Introduced PostHogClient function to initialize a PostHog client instance with configuration from environment variables.

Assessment against linked issues

Objective Addressed Explanation
Create OG Image Component for shared Articles (#1066)

Possibly related PRs

Suggested reviewers

  • NiallJoeMaher

🐇 In the fields where the wildflowers sway,
I crafted images bright as the day.
With PostHog's magic, I capture the scene,
For every share, let our colors gleam!
So hop along, let the graphics play,
In the world of OG, we’ll lead the way! 🌼✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 774050f and 8ec71cd.

📒 Files selected for processing (1)
  • app/og/route.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/og/route.tsx

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.

@github-actions
Copy link

Hello @South-IN, thanks for opening your first Pull Request. The maintainers will review this Pull Request and provide feedback as soon as possible. Keep up the great work!

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

🧹 Outside diff range and nitpick comments (3)
app/posthog.ts (1)

3-8: Overall structure looks good, but consider some improvements.

The PostHogClient function is well-structured and correctly initializes the PostHog client using environment variables. However, there are a few areas that could be improved:

  1. Error handling for missing environment variables:
    The current implementation doesn't handle cases where NEXT_PUBLIC_POSTHOG_KEY is not set, which could lead to unexpected behavior.

  2. Exception handling:
    The PostHog constructor might throw exceptions, which are currently not caught.

  3. Type safety:
    Consider using TypeScript to improve type safety and developer experience.

Here's a suggested implementation addressing these points:

import { PostHog } from 'posthog-node';

export default function PostHogClient(): PostHog | null {
  const posthogKey = process.env.NEXT_PUBLIC_POSTHOG_KEY;
  if (!posthogKey) {
    console.error('PostHog key is not set in environment variables');
    return null;
  }

  try {
    const posthogClient = new PostHog(posthogKey, {
      host: process.env.NEXT_PUBLIC_POSTHOG_HOST
    });
    return posthogClient;
  } catch (error) {
    console.error('Failed to initialize PostHog client:', error);
    return null;
  }
}

This implementation:

  1. Checks for the presence of the PostHog key.
  2. Uses a try-catch block to handle potential exceptions.
  3. Uses TypeScript for improved type safety.
  4. Returns null in error cases, allowing the caller to handle the absence of a client gracefully.
app/og/route.tsx (2)

Line range hint 24-28: Add error handling for font data fetching.

The code fetches font data from an external URL without handling potential errors. This could lead to unhandled exceptions if the fetch fails. Consider adding error handling to manage such scenarios gracefully.

Apply this diff to fix the issue:


93-102: Use relative URLs for images to improve maintainability.

The src attribute for images uses absolute URLs, which can lead to issues if the domain changes. Replace them with relative URLs or use the origin variable to construct the full URL dynamically.

Apply this diff to improve:

Ensure the image exists at the specified path on your server.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9f567e9 and f315757.

⛔ Files ignored due to path filters (5)
  • package.json is excluded by !**/*.json
  • public/images/og/noise.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/planet.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/stars.svg is excluded by !**/*.svg, !**/*.svg
  • public/images/og/waves.svg is excluded by !**/*.svg, !**/*.svg
📒 Files selected for processing (2)
  • app/og/route.tsx (5 hunks)
  • app/posthog.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (3)
app/posthog.ts (1)

1-1: LGTM: Import statement is correct.

The import of PostHog from 'posthog-node' is appropriate for initializing the PostHog client.

app/og/route.tsx (2)

178-179: ⚠️ Potential issue

Remove conflicting Tailwind CSS classes.

In the tw attribute, both bg-gradient-to-r and bg-red-500 are used together, which might conflict. Since you're specifying a custom gradient in the style, you can remove bg-red-500.

Apply this diff to fix:

Likely invalid or redundant comment.


14-17: Verify that PostHog events are capturing correctly.

Ensure that the posthogClient.capture method is sending events as expected. It's important to verify that the event data, including distinctId and event name, are correctly recorded in PostHog.

Run the following script to check for issues in event capturing:

Ensure that the events are appearing in PostHog with the correct properties.

app/posthog.ts Outdated
Comment on lines 4 to 6
const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY||"",{
host: process.env.NEXT_PUBLIC_POSTHOG_HOST
})
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security concern: Potential exposure of PostHog key to client-side.

The use of environment variables prefixed with NEXT_PUBLIC_ for the PostHog key and host is concerning. In Next.js, variables prefixed with NEXT_PUBLIC_ are exposed to the browser, which could potentially expose your PostHog API key to client-side code.

Consider renaming these environment variables to remove the NEXT_PUBLIC_ prefix:

- const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY||"",{
-     host: process.env.NEXT_PUBLIC_POSTHOG_HOST
+ const posthogClient = new PostHog(process.env.POSTHOG_KEY||"",{
+     host: process.env.POSTHOG_HOST

Also, update any configuration files or deployment scripts to use these new variable names.

📝 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
const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY||"",{
host: process.env.NEXT_PUBLIC_POSTHOG_HOST
})
const posthogClient = new PostHog(process.env.POSTHOG_KEY||"",{
host: process.env.POSTHOG_HOST
})

app/og/route.tsx Outdated
Comment on lines 15 to 16
distinctId:"south-in",
event:"Og image generated"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid hardcoding 'distinctId' to prevent PII leakage.

Using a hardcoded distinctId ("south-in") in posthogClient.capture and postHog.getAllFlags can lead to security and privacy concerns, as it may expose personally identifiable information (PII). Instead, consider dynamically generating the distinctId based on the user's session or anonymized data.

Apply this diff to fix the issue:

...

Also applies to: 218-219

app/og/route.tsx Outdated
Comment on lines 11 to 12
const posthogClient = PostHogClient()
const flags = await getData()
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

Optimize 'getData' function placement and usage.

The getData function is declared after it's called, which can affect readability. Additionally, creating a new PostHog client inside getData leads to multiple instances. Pass the existing posthogClient to getData and consider moving the function above its usage.

Apply this diff to refactor:

...
...

Also applies to: 216-220

app/og/route.tsx Outdated
Comment on lines 112 to 114
lineClamp: 3,

}}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace invalid CSS property 'lineClamp' with proper text truncation.

The lineClamp style property is not standard in CSS. To truncate text after a certain number of lines, use the -webkit-line-clamp property along with other necessary styles for cross-browser support.

Apply this diff to fix the issue:

Alternatively, if you're using Tailwind CSS with the @tailwindcss/line-clamp plugin, you can simplify it:

Ensure the plugin is installed and configured correctly.

Committable suggestion was skipped due to low confidence.

Copy link
Contributor

@NiallJoeMaher NiallJoeMaher left a comment

Choose a reason for hiding this comment

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

This looks so cool! Well done. 🥇

A few small changes.

  • Addng some padding to the surrounding lines.
  • You can delete the author name and article tag for the moment because I forgot I use this for the profile page too and will need to figure out how to separate.
  • You can remove the feature flag for now (since without the article tag and the user it'll be safe to push to production). But major kudos for setting it up and doing the screen recording, it made my life much easier.
  • Add text-balance to the title so it flows a little more evenly.

375733569-1a427935-6e32-41a3-876e-fb310a91e35b

@South-IN
Copy link
Contributor Author

Thank you for the feedback.
I'll make the required changes.

@South-IN
Copy link
Contributor Author

Component after requested changes :

image

  • Please let me know incase of more changes.

@github-actions
Copy link

Uh oh! @South-IN, the image you shared is missing helpful alt text. Check #1107 (comment).

Alt text is an invisible description that helps screen readers describe images to blind or low-vision users. If you are using markdown to display images, add your alt text inside the brackets of the markdown image.

Learn more about alt text at Basic writing and formatting syntax: images on GitHub Docs.

@NiallJoeMaher
Copy link
Contributor

Just linting issues now so if you run npm run prettier:fix you should be good to go

@vercel
Copy link

vercel bot commented Oct 16, 2024

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

Name Status Preview Comments Updated (UTC)
codu ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 16, 2024 8:54pm

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.

Create OG Image Component for shared Articles

2 participants