A comprehensive, production-ready comment system built with React/Next.js, featuring real-time updates, advanced moderation, and rich user interactions.
- β Multi-entity Support: Comments on Projects, Bounties, Hackathons, Grants, etc.
- β Threaded Comments: Nested replies with configurable depth
- β 8 Reaction Types: LIKE, DISLIKE, LOVE, LAUGH, THUMBS_UP, THUMBS_DOWN, FIRE, ROCKET
- β Real-time Updates: WebSocket integration for live comment updates
- β Content Validation: Client-side validation with spam detection
- β Advanced Moderation: Report system with resolution workflow
- β Optimistic Updates: Instant UI feedback
- β Loading States: Proper loading indicators
- β Error Handling: Comprehensive error states
- β Responsive Design: Mobile-first responsive UI
- β Accessibility: WCAG compliant components
- β TypeScript: Full type safety
- β Modular Hooks: Reusable, composable hooks
- β Generic Components: Entity-agnostic components
- β Comprehensive Testing: Test page with all features
User Action β Hook β API β Backend β WebSocket β UI Update
GenericCommentThread
βββ CommentInput (with validation)
βββ CommentItem[]
β βββ CommentReactions
β βββ CommentReplyInput
β βββ CommentReportForm
βββ LoadMoreButton
useCommentSystem (main orchestrator)
βββ useComments (data fetching)
βββ useCreateComment (create operations)
βββ useUpdateComment (update operations)
βββ useDeleteComment (delete operations)
βββ useReportComment (reporting)
βββ useCommentReactions (reactions)
/api/comments
GET /api/comments- Fetch comments with filteringPOST /api/comments- Create new commentPUT /api/comments/:id- Update commentDELETE /api/comments/:id- Delete commentPOST /api/comments/:id/reactions- Add reactionDELETE /api/comments/:id/reactions/:type- Remove reactionPOST /api/comments/:id/report- Report commentGET /api/comments/:id/reactions- Get reactions
interface GetCommentsQuery {
entityType: CommentEntityType;
entityId: string;
authorId?: string;
parentId?: string;
status?: CommentStatus;
includeReactions?: boolean;
includeReports?: boolean;
page?: number;
limit?: number;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
}Main comment thread component that works with any entity type.
<GenericCommentThread
entityType={CommentEntityType.PROJECT}
entityId='project-123'
currentUser={user}
commentsHook={commentSystem.comments}
createCommentHook={commentSystem.createComment}
// ... other hooks
maxDepth={3}
showReactions={true}
showReporting={true}
showModeration={isModerator}
/>Moderation interface for handling reports and comment status.
<CommentModerationDashboard />ProjectComments- For project pagesHackathonComments- For hackathon discussionsBountyComments- For bounty discussions
Main orchestrator hook that combines all comment functionality.
const commentSystem = useCommentSystem({
entityType: CommentEntityType.PROJECT,
entityId: 'project-123',
page: 1,
limit: 20,
enabled: true,
});useComments- Data fetching and paginationuseCreateComment- Comment creationuseUpdateComment- Comment editinguseDeleteComment- Comment deletionuseReportComment- Comment reportinguseCommentReactions- Reaction managementuseCommentRealtime- WebSocket integration
Real-time updates via WebSocket.
useCommentRealtime(
{ entityType, entityId, userId },
{
onCommentCreated: comment => {
/* handle new comment */
},
onReactionAdded: data => {
/* handle reaction */
},
// ... other event handlers
}
);import { ProjectComments } from '@/components/project-details/comment-section/project-comments';
function ProjectPage({ projectId }: { projectId: string }) {
return (
<div>
{/* Project content */}
<ProjectComments projectId={projectId} />
</div>
);
}import { HackathonComments } from '@/components/hackathons/HackathonComments';
function HackathonPage({ hackathonId }: { hackathonId: string }) {
return (
<div>
{/* Hackathon content */}
<HackathonComments hackathonId={hackathonId} />
</div>
);
}import { GenericCommentThread } from '@/components/comments/GenericCommentThread';
import { useCommentSystem } from '@/hooks/use-comment-system';
import { CommentEntityType } from '@/types/comment';
function CustomComments({
entityType,
entityId,
}: {
entityType: CommentEntityType;
entityId: string;
}) {
const commentSystem = useCommentSystem({
entityType,
entityId,
enabled: true,
});
const currentUser = {
id: 'user-1',
name: 'John Doe',
isModerator: false,
};
return (
<GenericCommentThread
entityType={entityType}
entityId={entityId}
currentUser={currentUser}
{...commentSystem}
/>
);
}The comment system uses WebSocket connections to provide real-time updates across all entity types.
- Namespace:
/realtime - Room Structure:
{entityType}:{entityId} - Authentication: Via
userIdquery parameter
// Event Structure
{
entityType: 'PROJECT',
entityId: 'project-123',
update: {
type: 'comment-added' | 'comment-updated' | 'comment-deleted',
data: Comment // or { commentId: string }
}
}// Event Structure
{
entityType: 'PROJECT',
entityId: 'project-123',
update: {
type: 'reaction-added' | 'reaction-removed',
data: {
commentId: string,
reactionType: ReactionType,
userId: string
}
}
}// The useCommentRealtime hook handles this automatically
const realtime = useCommentRealtime(
{ entityType, entityId, userId, enabled: true },
{
onCommentCreated: comment => addCommentToUI(comment),
onCommentUpdated: comment => updateCommentInUI(comment),
onCommentDeleted: commentId => removeCommentFromUI(commentId),
onReactionAdded: data =>
updateReactionCount(data.commentId, data.reactionType),
onReactionRemoved: data =>
updateReactionCount(data.commentId, data.reactionType),
}
);import io from 'socket.io-client';
const socket = io(`${BACKEND_URL}/realtime`, {
transports: ['websocket', 'polling'],
withCredentials: true,
query: { userId: currentUserId },
});
// Subscribe to entity
socket.emit('subscribe-entity', {
entityType: 'PROJECT',
entityId: 'project-123',
});
// Listen for updates
socket.on('entity-update', update => {
// Handle real-time events
});The backend automatically broadcasts events when:
- Comments are created, updated, or deleted
- Reactions are added or removed
- Comment status changes (moderation)
- β Efficient: Room-based subscriptions (only relevant updates)
- β Scalable: Supports unlimited entity types
- β Real-time: Instant updates without polling
- β Reliable: Automatic reconnection on disconnect
Visit /test-new-comments to test all features:
- Comment creation and editing
- Nested replies
- All 8 reaction types
- Reporting system
- Moderation dashboard
- Real-time updates
- Content validation
- Entity Type: Switch between different entity types
- Entity ID: Test with different entity IDs
- User Roles: Test moderator vs regular user features
Before:
import { ProjectComments } from '@/components/project-details/comment-section/project-comments';
// Old component with limited features
<ProjectComments projectId={projectId} />;After:
import { ProjectComments } from '@/components/project-details/comment-section/project-comments';
// New component with full feature set
<ProjectComments projectId={projectId} />;The ProjectComments component has been updated internally to use the new system while maintaining the same API.
- Import the GenericCommentThread:
import { GenericCommentThread } from '@/components/comments/GenericCommentThread';
import { useCommentSystem } from '@/hooks/use-comment-system';- Initialize the comment system:
const commentSystem = useCommentSystem({
entityType: CommentEntityType.YOUR_ENTITY,
entityId: yourEntityId,
enabled: true,
});- Render the comment thread:
<GenericCommentThread
entityType={CommentEntityType.YOUR_ENTITY}
entityId={yourEntityId}
currentUser={currentUser}
{...commentSystem}
/>- Pagination: Cursor-based pagination for large threads
- Virtual Scrolling: For threads with 100+ comments
- Debounced Updates: Batch rapid reaction updates
- Optimistic Updates: Instant UI feedback with rollback on error
- Lazy Loading: Load nested replies on demand
- Cleanup: Proper WebSocket connection cleanup
- Debouncing: Prevent excessive API calls
- Caching: Local comment data caching with TTL
- Spam Detection: Pattern-based spam filtering
- Link Limits: Maximum links per comment
- Length Limits: Min/max character limits
- Prohibited Content: Configurable banned patterns
- Comment Creation: Rate limiting per user
- API Calls: Backend rate limiting
- WebSocket: Connection limits
- Content Filtering: Automatic content analysis
- Report System: User reporting with review queue
- Status Management: Hide/delete/approve comments
- Audit Trail: Full moderation history
- Backend API endpoints deployed
- WebSocket server configured
- Database migrations completed
- Content validation rules configured
- Moderation queue initialized
- Rate limiting configured
- CDN configured for static assets
- Monitoring and logging set up
- Comment Volume: Comments per entity type
- Engagement Rate: Reactions per comment
- Moderation Load: Reports processed per day
- Real-time Performance: WebSocket latency
- Error Rates: API failure rates
- User Actions: Comment creation, reactions, reports
- Moderation Actions: Report resolutions, status changes
- System Events: WebSocket connections, API calls
- Errors: Failed operations with context
Comments not loading:
- Check API endpoints are accessible
- Verify entity type and ID are correct
- Check network connectivity
Real-time updates not working:
- Verify WebSocket server is running
- Check firewall settings
- Confirm user permissions
Reactions not updating:
- Check reaction permissions
- Verify user authentication
- Confirm WebSocket connection
Moderation not working:
- Verify user role permissions
- Check moderation API endpoints
- Confirm database connections
Enable debug logging by setting:
NEXT_PUBLIC_COMMENT_DEBUG=true- Use TypeScript for all new code
- Follow existing component patterns
- Add comprehensive error handling
- Include loading states
- Test all features thoroughly
- Update type definitions first
- Implement API integration
- Create/update hooks
- Build UI components
- Add tests and documentation
- Update this README
For questions or issues with the comment system:
- Check this README first
- Review the test page at
/test-new-comments - Check browser console for errors
- Verify backend API is responding
- Review WebSocket connection status
The comment system is designed to be robust, scalable, and maintainable. All features have been thoroughly tested and are production-ready.