Skip to content

Conversation

@thrupthi22
Copy link

@thrupthi22 thrupthi22 commented Aug 1, 2025

📝 Description
This PR introduces a website visitor counter, which is displayed in the footer of the application. This feature provides a dynamic way to show user engagement on the site.

🔗 Linked Issues
Closes #63

🧪 Type of Change
[x] ✨ New feature (non-breaking change which adds functionality)

🔄 Changes Made
Backend:

Created a new Visitor model to store the count in the database.

Added a visitorController with logic to increment and return the count.

Established a new API endpoint at /api/visitors/count.

Frontend:

Modified the Footer.jsx component to fetch the visitor count from the new API endpoint on component mount.

Integrated the display of the visitor count into the existing footer UI.

Configuration:

Updated vite.config.js to proxy API requests to the backend during development.

Modified config/db.js to include TLS options, resolving SSL connection errors with MongoDB Atlas. Testing
[x] I have tested the changes locally

[ ] I have added/updated tests for my changes

[x] All existing tests pass

[x] I have tested on multiple browsers (if frontend changes)

[x] I have tested the API endpoints (if backend changes)

Test Cases
Loaded the homepage and confirmed the "Visitors:" text appears in the footer and updates with a number.

Refreshed the page multiple times and verified that the visitor count correctly increments by one each time.

Inspected the browser's Network tab to confirm a successful 200 OK response from the /api/visitors/count endpoint.

Monitored the backend terminal to ensure no database connection errors were logged after the final fix.

📋 Checklist
[x] My code follows the project's style guidelines

[x] I have performed a self-review of my code

[x] I have commented my code, particularly in hard-to-understand areas

[ ] I have made corresponding changes to the documentation

[x] My changes generate no new warnings

[ ] I have added tests that prove my fix is effective or that my feature works

[x] New and existing unit tests pass locally with my changes

[ ] Any dependent changes have been merged and published in downstream modules

🌟 GSSoC Participation
[x] I am participating in GSSoC 2025
🤝 Contribution Guidelines
[x] I have read and followed the project's contributing guidelines

[x] I have checked that my PR doesn't duplicate an existing one

[x] I have ensured my branch is up to date with the main branch

[x] I agree to follow the project's Code of Conduct

Summary by CodeRabbit

  • New Features

    • Added a visitor counter to the website footer, displaying the total number of visits.
    • Visitor count is automatically fetched and updated from the backend.
    • Introduced a backend API endpoint to retrieve and increment the visitor count.
  • Bug Fixes

    • Improved error handling for visitor count fetch failures, displaying 'N/A' if the request fails.
  • Chores

    • Updated backend database connection logic for improved security and logging.
    • Configured frontend development server to proxy API requests to the backend.

@vercel
Copy link

vercel bot commented Aug 1, 2025

@thrupthi22 is attempting to deploy a commit to the bunty's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link

coderabbitai bot commented Aug 1, 2025

Walkthrough

A visitor count feature was implemented across the backend and frontend. Backend changes include a new Mongoose model, controller, and route for incrementing and retrieving the visitor count, along with MongoDB connection updates. The frontend Footer component now fetches and displays the visitor count, with Vite configured to proxy API requests.

Changes

Cohort / File(s) Change Summary
Visitor Count Backend Implementation
Backend/models/Visitor.js, Backend/controllers/visitorController.js, Backend/routes/visitorRoutes.js, Backend/index.js
Introduced a Mongoose Visitor model, a controller to increment and return the visitor count, a new route /api/visitors/count, and mounted the route in the backend server.
MongoDB Connection Refactor
Backend/config/db.js
Updated MongoDB connection logic to use TLS options, improved logging, removed dotenv import, and changed export to the connection function.
Frontend Footer Visitor Count
Frontend/src/components/Footer.jsx
Enhanced the Footer component to fetch and display the visitor count from the backend API, including error handling and animation.
Frontend Proxy Configuration
Frontend/vite.config.js
Added a Vite server proxy to forward /api requests to the backend server during development.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant FooterComponent
  participant FrontendServer
  participant BackendServer
  participant VisitorController
  participant MongoDB

  User->>FooterComponent: Loads page
  FooterComponent->>FrontendServer: GET /api/visitors/count
  FrontendServer->>BackendServer: Proxies /api/visitors/count
  BackendServer->>VisitorController: Route handler invoked
  VisitorController->>MongoDB: findOneAndUpdate({name: 'site_stats'}, {$inc: {count: 1}})
  MongoDB-->>VisitorController: Returns updated count
  VisitorController-->>BackendServer: Responds with count
  BackendServer-->>FrontendServer: Forwards count
  FrontendServer-->>FooterComponent: Returns count
  FooterComponent-->>User: Displays visitor count in footer
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Assessment against linked issues

Objective Addressed Explanation
Add website visitors count in the footer (#63)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Suggested labels

enhancement, Backend, GSSOC-25

Suggested reviewers

  • RamakrushnaBiswal

Poem

A bunny hopped across the code,
Counting visitors as they strode.
The backend tallied every guest,
The frontend showed the growing quest.
Now in the footer, clear and bright,
The count appears—a happy sight!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 generate unit tests to generate unit tests 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.

Copy link

@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

🧹 Nitpick comments (1)
Backend/models/Visitor.js (1)

3-13: Consider schema design improvements for better maintainability.

The current schema works but could be enhanced:

  1. The name field with a default value suggests a single-document pattern. Consider if this field is necessary or if you want to support multiple counters in the future.
  2. Adding timestamps could provide valuable analytics data.
 const VisitorSchema = new mongoose.Schema({
-    name: {
-        type: String,
-        required: true,
-        default: 'site_stats'
-    },
     count: {
         type: Number,
-        default: 0
+        default: 0,
+        min: 0
     }
-});
+}, {
+    timestamps: true
+});

Alternatively, if you plan to support multiple counters, keep the name field but make it more explicit:

     name: {
         type: String,
         required: true,
-        default: 'site_stats'
+        unique: true
     },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 96f6f0d and 597518f.

⛔ Files ignored due to path filters (1)
  • Backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • Backend/config/db.js (1 hunks)
  • Backend/controllers/visitorController.js (1 hunks)
  • Backend/index.js (1 hunks)
  • Backend/models/Visitor.js (1 hunks)
  • Backend/routes/visitorRoutes.js (1 hunks)
  • Frontend/src/components/Footer.jsx (12 hunks)
  • Frontend/vite.config.js (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
Backend/index.js (1)
Backend/routes/visitorRoutes.js (2)
  • require (3-3)
  • express (1-1)
Backend/controllers/visitorController.js (1)
Backend/routes/visitorRoutes.js (1)
  • require (3-3)
🔇 Additional comments (13)
Frontend/vite.config.js (1)

8-17: LGTM! Well-configured development proxy setup.

The proxy configuration correctly forwards API requests to the backend server during development. The changeOrigin: true and secure: false options are appropriate for local development without HTTPS.

Backend/index.js (2)

8-9: LGTM! Standard Express route integration.

The import and setup follows Express.js conventions properly.


22-23: Endpoint Path Consistency Verified

The frontend in Frontend/src/components/Footer.jsx is calling /api/visitors/count, which matches the backend mount of /api/visitors with a /count route. No changes needed.

Backend/routes/visitorRoutes.js (1)

5-6: LGTM! Standard route definition with a note on HTTP method choice.

The route correctly maps to /api/visitors/count when mounted. While using GET for an operation that modifies state (incrementing count) isn't strictly RESTful, it's an acceptable pattern for simple visitor counters and provides better caching behavior.

Backend/controllers/visitorController.js (1)

4-16: Excellent implementation with proper concurrency handling!

This controller demonstrates several best practices:

  1. Atomic operations: Using $inc with findOneAndUpdate prevents race conditions when multiple users visit simultaneously
  2. Upsert pattern: Creates the document if it doesn't exist, handling the initial state gracefully
  3. Proper error handling: Includes try-catch with appropriate HTTP status codes and error logging
  4. Clean response format: Returns a simple, consistent JSON structure

The implementation is robust and production-ready.

Backend/config/db.js (2)

13-13: Good improvement: Enhanced connection logging.

Storing the connection result and logging the specific host provides better debugging information compared to generic success messages.


15-16: Good improvement: Enhanced error handling.

The formatted error message and explicit process exit provide clearer debugging information and proper application termination on connection failure.

Frontend/src/components/Footer.jsx (6)

4-4: Good practice: Proper React hooks import.

Adding useEffect to the existing import statement maintains clean import organization.


12-12: Good state management: Visitor count initialization.

Initializing visitorCount to null allows for proper loading state handling and distinguishes between "loading" and "zero visitors".


15-33: Well-implemented API fetching with proper error handling.

The useEffect implementation follows React best practices:

  • Async function defined inside useEffect
  • Proper error handling with try-catch
  • HTTP status validation
  • Graceful fallback to 'N/A' on error
  • Empty dependency array for single execution on mount

255-262: Excellent UI integration with loading state.

The visitor count display includes:

  • Proper loading state (... while fetching)
  • Conditional rendering based on state
  • Consistent styling and animation
  • Appropriate placement in the footer

26-28: Good error handling strategy.

Logging the error for debugging while setting a user-friendly fallback value ('N/A') provides a good user experience even when the API fails.


19-19: Proxy configuration verified for /api endpoint

The Vite config (in vite.config.js) already includes a server proxy for '/api'http://localhost:5000, so fetch('/api/visitors/count') will be correctly forwarded. No changes to the proxy setup are required. Ensure that your backend exposes a /visitors/count route and returns the expected response.

Comment on lines +9 to +10
tls: true,
tlsAllowInvalidCertificates: true, // Use this for development only
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security concern: TLS certificate validation disabled.

The tlsAllowInvalidCertificates: true option disables certificate validation, which poses a security risk. While acceptable for development, ensure this is not used in production environments.

Consider using environment-based configuration:

-      tls: true,
-      tlsAllowInvalidCertificates: true, // Use this for development only
+      tls: true,
+      tlsAllowInvalidCertificates: process.env.NODE_ENV === 'development'
📝 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
tls: true,
tlsAllowInvalidCertificates: true, // Use this for development only
tls: true,
tlsAllowInvalidCertificates: process.env.NODE_ENV === 'development'
🤖 Prompt for AI Agents
In Backend/config/db.js around lines 9 to 10, the option
tlsAllowInvalidCertificates is set to true, disabling TLS certificate validation
and posing a security risk. Modify the code to conditionally set
tlsAllowInvalidCertificates based on the environment, enabling it only in
development and disabling it in production by using an environment variable
check (e.g., process.env.NODE_ENV). This ensures secure TLS validation in
production while allowing flexibility during development.

@vercel
Copy link

vercel bot commented Aug 1, 2025

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

Name Status Preview Comments Updated (UTC)
honor-box ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 1, 2025 0:10am

@RamakrushnaBiswal
Copy link
Owner

image @thrupthi22 its not working

@thrupthi22
Copy link
Author

@RamakrushnaBiswal Thank you for the feedback! I understand why it's not working on your end. The feature requires a MONGO_URI environment variable to connect to a database. Since that's a secret key, the feature won't work without a local .env file configured for testing

@RamakrushnaBiswal
Copy link
Owner

RamakrushnaBiswal commented Aug 6, 2025

hi @thrupthi22 sorry for late response
but i am added env in production MONOG_URI

@thrupthi22
Copy link
Author

hi @RamakrushnaBiswal
The issue you're seeing is likely happening in your local development environment. The production MONGO_URI isn't accessible when running the code on your own computer, which would cause the "N/A" error you see.

To find the exact local error, could you please check your browser's developer tools?

With the project running locally, press F12 to open the tools.

Go to the "Network" tab.

The request to /api/visitors/count will probably be red. The Status Code (like 404 or 500) will tell us exactly what's going wrong on your machine.

I'm happy to help fix whatever the error is. Thanks!

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.

[FEATURE]: Add website visitors count in the footer

2 participants