Relevant source files
The following files were used as context for generating this wiki page:
Troubleshooting in the Comp AI platform involves diagnosing and resolving issues across various layers, from local development environment setup to API request handling. This guide provides insights into common problems and their solutions, focusing on environment configuration, database management, and API error responses. Understanding these areas is crucial for maintaining a smooth development workflow and ensuring the application functions as expected.
Local Development Environment Troubleshooting
Setting up the local development environment for Comp AI requires specific prerequisites and careful configuration of environment variables and the database. Issues in these areas are common and can prevent the application from starting or functioning correctly.
Prerequisites and Initial Setup
Ensure your system meets the minimum software requirements before attempting to run Comp AI locally.
Verify Prerequisites
Confirm that the following software is installed with the specified versions:
- Node.js: Version
>=20.x - Bun: Version
>=1.1.36 - Postgres: Version
>=15.x
If any of these are not met, update or install them accordingly.
- Node.js: Version
Clone Repository and Install Dependencies
- Clone the Comp AI repository:
git clone https://github.com/trycompai/comp.git - Navigate to the project directory:
cd comp - Install dependencies using Bun:
bun install
- Clone the Comp AI repository:
Sources: README.md:65-71, README.md:83-91
Environment Variable Configuration
Incorrect or missing environment variables are a frequent source of issues. Comp AI requires several .env files to be correctly populated.
Required .env Files
Create the following .env files by copying from their respective .env.example counterparts:
comp/apps/app/.envcomp/apps/portal/.envcomp/packages/db/.env
cp apps/app/.env.example apps/app/.env
cp apps/portal/.env.example apps/portal/.env
cp packages/db/.env.example packages/db/.envCritical Environment Variables
Ensure comp/apps/app/.env contains at least the following variables:
| Variable | Description Sources: README.md:94-118, README.md:120-131, README.md:133-140
Hard-coding Environment Variables
Some environment variables might not load correctly from .env files, especially in certain development setups or environments. In such cases, the README.md explicitly recommends hard-coding these values directly into the relevant source files. This should be considered a temporary troubleshooting step and ideally resolved by fixing the environment variable loading mechanism.
Specific locations for hard-coding include:
- Google OAuth credentials:
GOOGLE_ID,GOOGLE_SECRETincomp/apps/portal/src/app/lib/auth.ts. - Redis (Upstash) credentials: Redis URL and TOKEN in
comp/packages/kv/src/index.ts. - Trigger.dev Project ID:
projectproperty incomp/apps/app/trigger.config.ts. Sources: README.md:141-143, README.md:156-158, README.md:167-169, README.md:176-178
Database Setup and Common Issues
The PostgreSQL database is a core component. Proper setup and migration are essential.
Start Database Container
Navigate to
packages/dband start the Docker container for PostgreSQL:cd packages/db bun docker:upVerify Credentials
The default credentials are:
- Database name:
comp - Username:
postgres - Password:
postgres
If you need to change the password, connect to the database and run:
ALTER USER postgres WITH PASSWORD 'new_password';- Database name:
Resolve "No function matches..." Error
If you encounter an error message like
HINT: No function matches the given name and argument types..., it indicates a missing database function. To fix this, run the following command, replacing<your_password>with your PostgreSQL password:psql "postgresql://postgres:<your_password>@localhost:5432/comp" -f ./packages/db/prisma/functionDefinition.sqlExpected output upon success is
CREATE FUNCTION. Ensure you use the correct port and database name for your setup.Generate Prisma Client and Apply Schema
After the database is running and any function definition issues are resolved:
- Generate the Prisma client:
bun db:generate - Push the schema to the database:
bun db:push - (Optional) Seed the database with initial data:
bun db:seed
- Generate the Prisma client:
Useful Database Commands
For further database management and troubleshooting:
bun db:studio: Open Prisma Studio to view/edit data.bun db:migrate: Run database migrations.bun docker:down: Stop the database container.bun docker:clean: Remove the database container and volume. Sources: README.md:181-183, README.md:185-188, README.md:190-192, README.md:194-203, README.md:205-212
API Error Handling
The Comp AI API includes specific mechanisms to handle common errors such as Cross-Origin Resource Sharing (CORS) issues and request validation failures.
CORS Exception Handling
The CorsExceptionFilter is a global exception filter designed to manage CORS headers on error responses. This is critical for allowing client applications (like the frontend) to communicate with the API, especially during development or when deployed across different domains.
How it Works
- Catches
HttpException: The filter intercepts anyHttpExceptionthrown by the API. - Extracts Origin: It reads the
Originheader from the incoming request. - Checks Allowed Origins: It compares the request origin against a predefined list of allowed origins. This list includes:
http://localhost:3000http://localhost:3001http://127.0.0.1:3000https://app.trycomp.aihttps://trycomp.ai- The value of
process.env.APP_URL
- Development Mode Flexibility: If
NODE_ENVis notproduction, it also allows origins containinglocalhost,127.0.0.1, orngrok. - Sets CORS Headers: If the origin is allowed, it sets
Access-Control-Allow-Origin,Access-Control-Allow-Credentials,Access-Control-Allow-Methods, andAccess-Control-Allow-Headerson the response. - Sends Error Response: Finally, it sends the original
HttpException's response body with the appropriate HTTP status code.
If you encounter CORS errors (e.g., "Access-Control-Allow-Origin header is not present") when making requests to the API, verify that your client's origin is included in the allowedOrigins list within the CorsExceptionFilter or that you are running in a development environment that permits your origin.
// apps/api/src/common/filters/cors-exception.filter.ts
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
} from '@nestjs/common';
import type { Response, Request } from 'express';
@Catch(HttpException)
export class CorsExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
const origin = request.headers.origin;
if (origin) {
const isDevelopment = process.env.NODE_ENV !== 'production';
const allowedOrigins = [
'http://localhost:3000',
'http://localhost:3001',
'http://127.0.0.1:3000',
'https://app.trycomp.ai',
'https://trycomp.ai',
process.env.APP_URL,
].filter(Boolean) as string[];
const isAllowed =
allowedOrigins.includes(origin) ||
(isDevelopment &&
(origin.includes('localhost') ||
origin.includes('127.0.0.1') ||
origin.includes('ngrok')));
if (isAllowed) {
response.setHeader('Access-Control-Allow-Origin', origin);
response.setHeader('Access-Control-Allow-Credentials', 'true');
response.setHeader(
'Access-Control-Allow-Methods',
'GET,POST,PUT,DELETE,PATCH,OPTIONS',
);
response.setHeader(
'Access-Control-Allow-Headers',
'Content-Type,Authorization,X-API-Key,X-Organization-Id',
);
}
}
response.status(status).json(exception.getResponse());
}
}Sources: apps/api/src/common/filters/cors-exception.filter.ts:1-42
Zod Validation Pipe
The ZodValidationPipe is a custom NestJS pipe used for validating incoming request data (e.g., body, query parameters) against a Zod schema. This ensures that data conforms to expected types and structures before being processed by controller handlers.
How it Works
- Constructor: It takes a
ZodSchemainstance during its creation. transformMethod: When applied to a route handler parameter, this method attempts to parse the incomingvalueusing the providedschema.- Validation Failure: If
schema.parse(value)throws an error (meaning the data does not match the schema), the pipe catches it and throws aBadRequestExceptionwith the message 'Validation failed'.
Using ZodValidationPipe helps enforce data integrity at the API boundary, preventing malformed requests from reaching business logic. When troubleshooting, if you receive a 400 Bad Request with the message 'Validation failed', it indicates that the request payload does not conform to the expected Zod schema for that endpoint.
// apps/api/src/common/pipes/zod-validation.pipe.ts
import {
ArgumentMetadata,
BadRequestException,
PipeTransform,
} from '@nestjs/common';
import { ZodSchema } from 'zod';
export class ZodValidationPipe implements PipeTransform {
constructor(private schema: ZodSchema) {}
transform(value: unknown, metadata: ArgumentMetadata) {
try {
const parsedValue = this.schema.parse(value);
return parsedValue;
} catch (error) {
throw new BadRequestException('Validation failed');
}
}
}Sources: apps/api/src/common/pipes/zod-validation.pipe.ts:1-15
API Request Flow with Error Handling
The following sequence diagram illustrates how an API request is processed, including the points where CORS and Zod validation errors might be handled.
Sources: apps/api/src/common/filters/cors-exception.filter.ts, apps/api/src/common/pipes/zod-validation.pipe.ts
On This Page
Local Development Environment TroubleshootingPrerequisites and Initial SetupVerify PrerequisitesClone Repository and Install DependenciesEnvironment Variable ConfigurationRequired .env FilesCritical Environment VariablesHard-coding Environment VariablesDatabase Setup and Common IssuesStart Database ContainerVerify CredentialsResolve "No function matches..." ErrorGenerate Prisma Client and Apply SchemaUseful Database CommandsAPI Error HandlingCORS Exception HandlingHow it WorksZod Validation PipeHow it WorksAPI Request Flow with Error Handling