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.
![]() |
![]() |
---|---|
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
firestore.rules
) Admins can manage posts and comments, approving or removing content.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>;
}
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 };
}
Finanarepublic is built on a modern Jamstack architecture using Next.js for the frontend and Firebase for backend services.
The architecture is designed to be highly interactive and engaging.
Security is a multi-layered concern, addressed at the middleware, application, and database levels.
AuthContext
.admin
, super_admin
). An admin user can perform privileged actions.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
}
}
}
middleware.ts
file acts as the first line of defense for incoming requests.
Content-Security-Policy
(in next.config.mjs
), X-Frame-Options
, and Strict-Transport-Security
./admin
, /dashboard
) to detect and block malicious actors./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();
}
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.
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.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.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.users
collection in Firestore.firestore.rules
ensure that a user can only write to their own document./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.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.Authorization
header using the Firebase Admin SDK.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:
localStorage
is more common for this.The project employs a minimalistic design philosophy, heavily influenced by the principles of clarity and focus.
Inter
) is used for all text, with a well-defined type scale for clear visual hierarchy.surface
, text
, interactive
) are used for consistency in both light and dark modes.