-
Notifications
You must be signed in to change notification settings - Fork 30
feat: Add website visitor counter (issue#63) #71
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
feat: Add website visitor counter (issue#63) #71
Conversation
|
@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. |
WalkthroughA 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~15 minutes Assessment against linked issues
Assessment against linked issues: Out-of-scope changesNo out-of-scope changes found. Suggested labels
Suggested reviewers
Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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:
- The
namefield 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.- 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
⛔ Files ignored due to path filters (1)
Backend/package-lock.jsonis 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: trueandsecure: falseoptions 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 VerifiedThe frontend in
Frontend/src/components/Footer.jsxis calling/api/visitors/count, which matches the backend mount of/api/visitorswith a/countroute. 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/countwhen 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:
- Atomic operations: Using
$incwithfindOneAndUpdateprevents race conditions when multiple users visit simultaneously- Upsert pattern: Creates the document if it doesn't exist, handling the initial state gracefully
- Proper error handling: Includes try-catch with appropriate HTTP status codes and error logging
- 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
useEffectto the existing import statement maintains clean import organization.
12-12: Good state management: Visitor count initialization.Initializing
visitorCounttonullallows for proper loading state handling and distinguishes between "loading" and "zero visitors".
15-33: Well-implemented API fetching with proper error handling.The
useEffectimplementation 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/apiendpointThe Vite config (in
vite.config.js) already includes a server proxy for'/api'→http://localhost:5000, sofetch('/api/visitors/count')will be correctly forwarded. No changes to the proxy setup are required. Ensure that your backend exposes a/visitors/countroute and returns the expected response.
| tls: true, | ||
| tlsAllowInvalidCertificates: true, // Use this for development only |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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.
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
@thrupthi22 its not working
|
|
@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 |
|
hi @thrupthi22 sorry for late response |
|
hi @RamakrushnaBiswal 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! |

📝 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
Bug Fixes
Chores