• Summary
  • ScreenShots
  • Detailed Breakdown of Features
  • Code Implementation Examples
  • Architecture Overview
  • Security Architecture
  • Tools & Stack
  • APIs
  • Database & Authentication
  • Cookie Management
  • Design Approach
  • contact

Project Alpha

Summary

Project Alpha is a full-stack financial data and community platform designed to provide users with real-time market insights, stock analysis tools, and a collaborative space for discussion.

It combines a rich set of financial data APIs with a sophisticated social platform, allowing users to track stocks, share insights, and engage with a community of fellow investors. The platform is built with a focus on performance, security, and a clean, minimalistic user experience.

ScreenShots

Detailed Breakdown of Features

User Authentication and Profiles

  • Authentication: Users can create accounts and sign in using email/password or Google OAuth. The system supports email verification and secure session management.
  • Profiles: Every user has a public profile page displaying their username, bio, and community statistics (reputation, post/comment count).
  • Profile Completion: A modal prompts users to complete their profiles (e.g., set a username) to improve community interaction.

Stock Analysis

  • Real-time Data: The platform provides real-time stock quotes, price charts, and key metrics.
  • Advanced Charting: Interactive charts display historical price data, technical indicators, and volume.
  • Financial Statements: Users can view income statements, balance sheets, and cash flow statements for individual companies.
  • Market Data: The application also provides data on market indices, economic indicators, insider trades, and more.

Community and Social Features

  • Post Creation: Users can create rich-text posts using the Lexical editor, tagging relevant stock tickers.
  • Community Feed: A central feed displays posts from the community, which can be sorted and filtered.
  • Voting System: Users can upvote or downvote posts and comments, contributing to a reputation system.
  • Commenting: Nested comments allow for threaded discussions on posts.

News and RSS

  • Aggregated News: A dedicated news section provides the latest financial news from various sources.
  • RSS Feed Management: Users and admins can add and manage RSS feeds to customize the news flow.

Search

  • Live Ticker Search: A powerful, debounced search bar in the navigation allows users to quickly find stock tickers.
  • Community Search: Users can search for posts and comments within the community section.

Admin Dashboard

  • User Management: Admins have a dashboard to manage users, including viewing profiles and adjusting reputation.
  • Content Moderation: (Inferred from firestore.rules) Admins can manage posts and comments, approving or removing content.
  • System Management: Admins can manage site-wide settings like RSS feeds and trusted domains.

Code Implementation Examples

Authentication Context

The AuthContext provides a global state for the current user's authentication status, leveraging Firebase Auth. It handles sign-in, sign-out, and retrieving user roles from custom claims.

// contexts/AuthContext.tsx

"use client";

import {
  createContext,
  useContext,
  useEffect,
  useState,
  ReactNode,
} from "react";
import { User, onAuthStateChanged, signOut } from "firebase/auth";
import { auth } from "@/lib/firebase";
// ... other imports

interface AuthContextType {
  user: AuthUser | null;
  loading: boolean;
  // ...
}

const AuthContext = createContext<AuthContextType>(/* ... */);

export const useAuth = () => {
  return useContext(AuthContext);
};

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<AuthUser | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (firebaseUser) => {
      if (firebaseUser) {
        // Get custom claims for roles
        const idTokenResult = await firebaseUser.getIdTokenResult();
        const customClaims = idTokenResult.claims;

        const authUser: AuthUser = {
          ...firebaseUser,
          role: customClaims.role as AdminRole,
          // ...
        };

        setUser(authUser);
      } else {
        setUser(null);
      }
      setLoading(false);
    });

    return () => unsubscribe();
  }, []);

  // ... signOutUser function

  const value = { user, loading /* ... */ };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

Data Fetching with Custom Hooks

The application uses custom hooks to encapsulate data-fetching logic, like this hook for fetching news articles.

// hooks/useNews.ts (Illustrative Example)

import { useState, useEffect } from "react";

export function useNews(ticker: string) {
  const [news, setNews] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!ticker) return;

    const fetchNews = async () => {
      setLoading(true);
      try {
        const response = await fetch(`/api/news?ticker=${ticker}`);
        const data = await response.json();
        setNews(data.articles || []);
      } catch (error) {
        console.error("Failed to fetch news:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchNews();
  }, [ticker]);

  return { news, loading };
}

Architecture Overview

System Architecture

Finanarepublic is built on a modern Jamstack architecture using Next.js for the frontend and Firebase for backend services.

  • Frontend: A Next.js application utilizing the App Router for server-side rendering (SSR) and static site generation (SSG), which ensures fast page loads and good SEO. React Server Components and Client Components are used to optimize rendering.
  • Backend: A combination of Next.js API Routes and Firebase services.
    • Next.js API Routes: Handle server-side logic, proxy requests to external financial APIs, and perform actions requiring server-side validation.
    • Firebase: Provides a suite of backend-as-a-service (BaaS) tools:
      • Firestore: A NoSQL database for storing user data, posts, comments, and other application state.
      • Firebase Authentication: Manages user identity and authentication.
      • Firebase Storage: Used for storing user-uploaded assets like profile pictures.
      • Firebase Admin SDK: Used in server-side environments for privileged operations like setting custom claims or bypassing security rules.

User Experience (UX) and Retention

The architecture is designed to be highly interactive and engaging.

  • Real-time Updates: Firebase's real-time capabilities can be used to push live updates for comments, posts, and notifications.
  • Optimistic UI: For actions like voting or commenting, the UI can be updated instantly while the backend request is processed in the background.
  • Minimalistic Design: A clean, uncluttered interface (discussed below) reduces cognitive load and focuses the user on data and content.
  • Engagement Hooks: Features like reputation, profile completion prompts, and notifications are designed to encourage continued user participation.

Security Architecture

Security is a multi-layered concern, addressed at the middleware, application, and database levels.

Authentication

  • Provider: Firebase Authentication handles the entire user lifecycle, including sign-up, sign-in, password reset, and OAuth integration.
  • Session Management: Firebase's client-side SDK manages user sessions and JWT (JSON Web Token) refresh automatically. The user's authentication state is shared throughout the app via the AuthContext.

Authorization

  • Role-Based Access Control (RBAC): The system uses Firebase Custom Claims to implement roles (e.g., admin, super_admin). An admin user can perform privileged actions.
  • Database Security Rules: firestore.rules provide the ultimate source of truth for data access control. These rules are evaluated on the server and cannot be bypassed by clients. They ensure that users can only read/write data they are permitted to.
// firestore.rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    // Helper function to check if user is admin
    function isAdmin() {
      return request.auth != null && request.auth.token.admin == true;
    }

    // Users can only update their own profile
    match /users/{userId} {
      allow read: if true; // Public profiles
      allow update: if request.auth.uid == userId;
      // ... other rules
    }

    // Posts can only be deleted by the author or an admin
    match /posts/{postId} {
      allow delete: if isAdmin() || request.auth.uid == resource.data.authorId;
      // ... other rules
    }
  }
}

Route & API Protection

  • Middleware: The middleware.ts file acts as the first line of defense for incoming requests.
    • Rate Limiting: Implements IP-based rate limiting for all API routes to prevent abuse.
    • Security Headers: Sets crucial security headers like Content-Security-Policy (in next.config.mjs), X-Frame-Options, and Strict-Transport-Security.
    • Decoy Routes: Sets up "honeypot" admin routes (/admin, /dashboard) to detect and block malicious actors.
    • CSRF Protection: Applies CSRF token validation to sensitive API endpoints (e.g., /api/admin/*).
// middleware.ts

import { NextRequest, NextResponse } from "next/server";
import RateLimiter from "@/lib/rateLimit";

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const ip = getClientIP(request);

  // Rate limit API routes
  if (pathname.startsWith("/api/")) {
    const rateLimitResult = await checkAPIRateLimit(request, ip);
    if (!rateLimitResult.allowed) {
      return new NextResponse("Rate limit exceeded", { status: 429 });
    }
  }

  // ... other security checks

  return NextResponse.next();
}

Tools & Stack

  • Framework: Next.js 15
  • Language: TypeScript
  • Backend: Firebase (Authentication, Firestore, Storage), Next.js API Routes
  • Styling: Tailwind CSS
  • UI: React
  • Text Editor: Lexical
  • Charting: Chart.js, Lightweight Charts, Recharts
  • Linting/Formatting: ESLint
  • Runtime: Node.js

APIs

The project exposes a comprehensive set of internal API endpoints via Next.js API Routes. These routes serve as a backend layer to fetch data from external sources or interact with Firebase Admin.

Financial Data APIs (Examples)

These endpoints fetch data from third-party financial APIs (like Financial Modeling Prep, Alpha Vantage, or Yahoo Finance) and are subject to rate limiting.

  • /api/stock-quote: Fetches a real-time quote for a given ticker.
  • /api/historical-chart: Retrieves historical price data.
  • /api/financial-statements/*: Endpoints for income, balance, and cash flow statements.
  • /api/news: Fetches news articles for a ticker or general market news.
  • /api/company-profile: Gets detailed company information.
  • /api/market-indices: Fethes major market index data.
  • /api/insider-trades: Retrieves data on insider trading activity.

Application APIs

These endpoints handle application-specific logic.

  • /api/search: Powers the live ticker search.
  • /api/profile/[username]: Fetches data for a user's profile page.
  • /api/account/delete: Handles user account deletion requests.
  • /api/csrf-token: Issues a CSRF token for secure form submissions.
  • /api/rss-feeds/*: Endpoints for managing user and admin RSS feeds.

Admin APIs

These endpoints are protected and can only be accessed by authenticated administrators.

  • /api/admin/users/[userId]: Manages a specific user.
  • /api/admin/reputation: Adjusts a user's reputation score.

Database & Authentication

User Management

  • Creation: Users are created in Firebase Authentication via the client-side SDK. Upon first sign-in, a corresponding user document is created in the users collection in Firestore.
  • Modification: Users can modify their own profile data (displayName, bio, etc.). The firestore.rules ensure that a user can only write to their own document.
  • Deletion: A user can request to delete their account via the /api/account/delete endpoint. This server-side function uses the Firebase Admin SDK to delete the user's Auth record and all associated data from Firestore.

Content Management

  • Post/Comment Creation: When a user submits a post or comment, the client writes a new document directly to the posts or comments collection in Firestore. The data is validated against the firestore.rules to ensure it has the correct structure and the user is authenticated.
  • External Creation: There is no evidence of an "external author terminal" API for creating posts. All content creation appears to be initiated by authenticated users through the client application. To implement this, a secure API endpoint protected by an API key or admin-only access would be required.

Session Management

  • Firebase SDK: Session management is handled almost entirely by the Firebase Authentication SDK on the client.
  • Token-Based: Upon successful login, the SDK receives a JWT ID token and a refresh token. The ID token is short-lived and sent with requests to backend resources. The SDK uses the long-lived refresh token to automatically get new ID tokens without requiring the user to log in again.
  • Server-Side Verification: Server-side API routes that require authentication verify the ID token sent in the Authorization header using the Firebase Admin SDK.

Cookie Management

The application primarily relies on Firebase's token management, which uses IndexedDB in the browser to store session information, not traditional session cookies. However, cookies may be used for other purposes:

  • CSRF Tokens: The CSRF protection mechanism may use a cookie to store the CSRF secret, which is then used to validate tokens on form submission.
  • Theme Preference: A cookie could be used to store the user's theme (dark/light) preference, although localStorage is more common for this.

Design Approach

The project employs a minimalistic design philosophy, heavily influenced by the principles of clarity and focus.

  • Typography: A clean, sans-serif font (Inter) is used for all text, with a well-defined type scale for clear visual hierarchy.
  • Color Palette: The color scheme is intentionally simple, built around black, white, and a neutral gray scale. This creates a professional, high-contrast aesthetic that is easy on the eyes and ensures that data visualizations (like charts) stand out. Semantic color tokens (surface, text, interactive) are used for consistency in both light and dark modes.
  • Layout: The layout is spacious and uncluttered. Ample white space is used to separate elements and guide the user's focus.
  • Component-Based: The UI is built from small, reusable components, ensuring a consistent look and feel across the entire application.