What Is the Purpose of the src Directory in OpenSEO? A Complete Architecture Guide
The src directory serves as the monolithic container for all OpenSEO application source code, organizing the TanStack Start bootstrap, server functions, shared utilities, type definitions, database layer, and middleware into a clean, layered architecture.
In the every-app/open-seo repository, the src folder represents the single source of truth for business logic and data handling. It implements a modular structure that separates concerns by responsibility—from API endpoints to database schemas—enabling both SaaS and self-hosted deployments to share identical code paths.
Overview of the src Directory Structure
The src directory follows a domain-driven organization where each subfolder owns a specific technical responsibility. This structure prevents circular dependencies and ensures that client-side and server-side code can safely share common utilities without leaking implementation details. According to the repository's source code, the directory contains seven primary areas of concern: server functions, shared utilities, type definitions, database schemas, middleware, and application entry points.
Core Subdirectories and Their Responsibilities
serverFunctions: The TanStack Server-Function API
The src/serverFunctions directory implements TanStack's server-function mechanism, exposing typed remote procedures that the React frontend calls for SEO operations. These files handle rank tracking, keyword research, and Lighthouse audits.
For example, src/serverFunctions/rank-tracking.ts exports functions that the UI consumes directly:
// Example React component consuming a server function
import { useServerFunction } from "@tanstack/react-start";
import { rankTracking } from "@/serverFunctions/rank-tracking";
export function RankTracker() {
const { mutateAsync: fetchRank } = useServerFunction(rankTracking);
const handleClick = async () => {
const result = await fetchRank({ domain: "example.com", keyword: "open seo" });
console.log(result);
};
return <button onClick={handleClick}>Check Rank</button>;
}
Source: src/serverFunctions/rank-tracking.ts
shared: Cross-Cutting Utilities
The src/shared folder houses stateless utilities used by both client and server contexts. These helpers keep the codebase DRY (Don't Repeat Yourself) by centralizing common logic like JSON parsing, colour palette generation, and Google Search Console wrappers.
A typical usage pattern involves importing helpers directly into components or server functions:
import { safeParseJSON } from "@/shared/json";
const data = safeParseJSON('{"foo":"bar"}');
if (data) {
console.log(data.foo); // "bar"
}
Source: src/shared/json.ts
types: Zod Schemas and TypeScript Definitions
Located in src/types, this directory contains TypeScript interfaces and Zod schemas that enforce data contracts with external APIs (DataForSEO, Google Search Console) and validate database inputs. The schemas ensure runtime type safety beyond compile-time checks.
For instance, keyword data structures are defined in src/types/schemas/keywords.ts:
import { z } from "zod";
export const KeywordSchema = z.object({
id: z.string(),
phrase: z.string(),
volume: z.number(),
difficulty: z.number(),
});
Source: src/types/schemas/keywords.ts
db: Database Abstraction with Drizzle
The src/db directory encapsulates all database concerns using Drizzle ORM. It contains schema definitions in schema.ts, migration utilities, and provider abstractions that allow the same codebase to run on SQLite (local development) or Postgres (production).
Database access occurs through the provider pattern:
import { db } from "@/db/provider";
export async function getProject(id: string) {
return await db.select().from(projects).where(eq(projects.id, id));
}
Source: src/db/provider.ts
middleware: Request Pre-Processing Pipeline
Files in src/middleware implement Express-like middleware that executes before every server function or HTTP request. This layer centralizes cross-cutting concerns like CSRF protection (createCsrfMiddleware), user authentication (ensureUser.ts), and global error handling (errorHandling.ts).
Entry Points and Application Bootstrap
src/start.ts: The TanStack Start Instance
The root file src/start.ts bootstraps the entire application by creating the TanStack React-Start instance. It wires the global middleware pipeline and configures CSRF protection for server functions:
// src/start.ts
import { createCsrfMiddleware, createStart } from "@tanstack/react-start";
import { globalServerFunctionMiddleware } from "@/serverFunctions/middleware";
const csrfMiddleware = createCsrfMiddleware({
filter: (ctx) => ctx.handlerType === "serverFn",
});
export const startInstance = createStart(() => ({
requestMiddleware: [csrfMiddleware],
functionMiddleware: globalServerFunctionMiddleware,
}));
Source: src/start.ts
src/routeTree.gen.ts: Client-Side Routing
This auto-generated file at the root of src defines the client-side route tree, mapping URLs to their corresponding React components. It bridges the file-system routing convention with the TanStack Router configuration.
How Code Flows Through the src Directory
Understanding the src directory requires tracing the request lifecycle:
- Bootstrap:
src/start.tsinitializes the application with middleware configurations. - Routing:
src/routeTree.gen.tsmatches incoming URLs to page components. - Middleware: Functions in
src/middlewareauthenticate the user and handle errors before business logic executes. - Server Functions: Logic in
src/serverFunctionsprocesses SEO data requests (rank checks, audits). - Validation:
src/typesZod schemas validate external API responses and user inputs. - Persistence:
src/dbproviders persist or retrieve data from SQLite/Postgres. - Sharing:
src/sharedutilities format the response data for the frontend.
Practical Examples: Working with src Code
When extending OpenSEO, developers interact with src through predictable patterns. Server functions import from shared and types, while the database layer remains isolated from UI concerns.
Database Schema Definition:
The src/db/schema.ts file defines table structures using Drizzle syntax, which the provider then exposes to server functions.
Middleware Application:
Authentication checks in src/middleware/ensureUser.ts run automatically for every server function call, eliminating the need to manually verify sessions in each business logic file.
Summary
- The
srcdirectory contains all application source code for OpenSEO, acting as the single source of truth for business logic. src/serverFunctionsexposes TanStack server functions for SEO operations like rank tracking and keyword research.src/sharedprovides cross-platform utilities (JSON parsing, billing logic) used by both client and server.src/typesmaintains Zod schemas and TypeScript definitions for external API validation.src/dbabstracts database access through Drizzle ORM with multi-provider support (Postgres/SQLite).src/middlewarecentralizes request pre-processing including authentication and CSRF protection.src/start.tsbootstraps the TanStack Start instance with global middleware configuration.
Frequently Asked Questions
What is the main entry point for the OpenSEO application?
The main entry point is src/start.ts, which creates the TanStack React-Start instance and configures global middleware including CSRF protection and server-function middleware pipelines. This file bootstraps the entire application before routing takes over.
How does OpenSEO handle database connections in the src directory?
Database connections are abstracted through src/db/provider.ts, which exports a configured Drizzle ORM instance. The same provider supports multiple backends (SQLite for local development, Postgres for production) via environment variables, ensuring src/db/schema.ts definitions work uniformly across deployment targets.
What is the purpose of the serverFunctions folder in src?
The src/serverFunctions directory implements TanStack's server-function API, exposing type-safe remote procedures that React components call directly. These functions handle SEO-specific operations—such as rank tracking in rank-tracking.ts and keyword research in keywords.ts—while running exclusively on the server for API key security and heavy computation.
Why does OpenSEO use Zod schemas in the src/types directory?
OpenSEO uses Zod schemas in src/types to enforce runtime validation of data exchanged with external APIs like DataForSEO and Google Search Console. These schemas—stored in files like src/types/schemas/keywords.ts—provide type safety beyond TypeScript compilation, catching malformed responses before they propagate into the application logic or database.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →