TrustNet empowers small-scale entrepreneurs and local businesses by giving them credible, verified digital identities. Traditional Know-Your-Customer (KYC) processes are too document-heavy for micro-businesses, street vendors, and home-based entrepreneurs. TrustNet solves this by offering community validation, UPI transaction-based trust signals, and analytics that help local entrepreneurs build and showcase their credibility online.
TrustNet/
β
βββ app/
β βββ page.tsx β Home page (frontend UI)
β βββ dashboard/
β β βββ page.tsx β Dashboard view for business insights
β βββ api/
β βββ users/
β β βββ route.ts β API endpoint for user management
β βββ auth/
β β βββ route.ts β OTP-based authentication API
β βββ business/
β βββ route.ts β Business profile CRUD operations
β
βββ components/
β βββ Navbar.tsx β Top navigation bar component
β βββ Footer.tsx β Footer component
β βββ BusinessCard.tsx β Displays business details and trust score
β βββ AnalyticsChart.tsx β Chart.js component for analytics dashboard
β
βββ lib/
β βββ db.ts β Database connection logic (PostgreSQL)
β βββ auth.ts β Authentication and session utilities
β βββ trustScore.ts β Core logic for trust score calculation
β βββ redis.ts β Redis caching configuration
β
βββ public/
β βββ logo.png β Project logo for README and UI
β
βββ styles/
β βββ globals.css β Global Tailwind CSS and style settings
β
βββ .env.local β Environment variables (not committed)
βββ next.config.js β Next.js configuration
βββ package.json β Dependencies and project metadata
βββ README.md β Project documentation
- Node.js 20 or higher
- PostgreSQL 15 or higher
- Redis 7 or higher
- Docker (optional but recommended)
- AWS or Azure account for deployment
Clone the repository git clone https://github.com/kalviumcommunityS62_1025_API-nauts_Full-Stack-With-NextjsAnd-AWS-Azure-Supply-Chain_TrustNet.git cd trustnet
Install dependencies npm install
Setup environment variables cp .env.example .env
Add your database URL, Redis URL, and required environment keys Run Prisma migrations npx prisma migrate dev
Seed initial data (optional) npx prisma db seed
Start the Next.js development server npm run dev
Visit http://localhost:3000 to view the application.
Build and run containers docker-compose up --build
The structure and technologies were chosen to maximize modularity, scalability, and performance across future sprints.
- Next.js 14 provides full-stack capabilities with built-in API routes, ensuring frontend and backend alignment.
- PostgreSQL with Prisma offers a robust ORM layer and easily maintainable schema evolution.
- Redis caching enhances performance for analytics and trust score computations.
- Docker ensures consistent development and production environments.
This structure supports collaborative scaling for future sprint pipelines where each subsystem (analytics, verification, dashboard) can evolve independently with minimal coupling.
Add a screenshot of your local application running below.
Example placeholder:
- Mobile app integration for field agents and vendors
- Advanced analytics with AI-driven trust prediction
- Multi-language support for vernacular inclusivity
- Integration with government micro-loan identity networks
| Role | Team Member | Key Responsibilities |
|---|---|---|
| Frontend Lead | Claudia Jerome | Next.js UI components, responsive design, analytics dashboard |
| Backend Lead | Tejas Philip Thomas | Database design, API routes, UPI verification system |
| Full-Stack & DevOps | Isaac Reji | Prisma schema, Redis integration, Docker setup, deployment |
| Quality Assurance | All Members | Testing, bug reporting, user experience validation |
We enabled strict mode to catch potential issues early:
"strict": trueensures all types are defined."noImplicitAny": trueprevents untyped variables."noUnusedLocals"and"noUnusedParameters"clean up unused code.
Our ESLint configuration extends next/core-web-vitals and Prettier rules to ensure clean, readable, and consistent code.
We enforce:
- No console logs in production.
- Mandatory semicolons.
- Double quotes for all strings.
We use Husky and lint-staged to automatically lint and format code before commits.
This ensures that no badly formatted code enters our repository.
When committing code that violates lint rules, Husky blocks the commit until all issues are fixed.
This document explains the environment variables needed for the TrustNet backend, their purposes, client vs server safety, how to replicate the setup using .env.example, and common pitfalls avoided.
| Variable | Purpose | Client-Side Safe? |
|---|---|---|
DATABASE_URL |
Connection string for the PostgreSQL database | No (Server-side only) |
JWT_SECRET |
Secret key for signing JSON Web Tokens for user authentication | No (Server-side only) |
NEXTAUTH_SECRET |
Secret used for NextAuth session encryption | No (Server-side only) |
REDIS_URL |
Connection URL for Redis server used for caching and session storage | No (Server-side only) |
NODE_ENV |
Defines environment mode (e.g., development, production) | No (Server-side only) |
UPI_SERVICE_URL |
URL for UPI verification service (mock during dev, real endpoint in production) | No (Server-side only) |
NEXTAUTH_URL |
Public URL of the application, used by NextAuth for redirect callbacks | Yes (safe to expose if needed) |
- All environment variables except
NEXTAUTH_URLare server-side only and must not be exposed in client-side bundles. - Ensure no sensitive variables have the
NEXT_PUBLIC_prefix, as Next.js exposes those to the browser. - Variables without
NEXT_PUBLIC_prefix are accessible only in API routes and server code viaprocess.env. - This separation protects secrets like database URLs, JWT secrets, and Redis connections from client exposure.
- Copy
.env.exampleto.envin your project root. - Replace placeholder values with your actual credentials and secrets:
- Update PostgreSQL connection string (
DATABASE_URL) - Generate strong secrets for
JWT_SECRETandNEXTAUTH_SECRET - Configure correct Redis connection URL (
REDIS_URL) - Point
UPI_SERVICE_URLto the appropriate service endpoint - Set
NEXTAUTH_URLto your deployed application URL
- Update PostgreSQL connection string (
- Add
.envto your.gitignorefile to prevent committing sensitive secrets to version control. - Restart your development or production server after modifying
.envto ensure all variables load correctly. - For deployment, use your cloud provider's environment variable configuration (AWS, Azure, Docker secrets, etc.) instead of local
.env.
- Exposing secrets accidentally: No sensitive variables are prefixed with
NEXT_PUBLIC_, avoiding client bundle exposure. - Not committing secrets: The
.env.exampleserves as a safe template only; the actual.envfile is excluded from version control. - Quotation usage: Values with special characters or URLs are wrapped in double quotes to avoid parsing errors.
- Runtime accessibility: Variables are accessed at runtime in server-side API routes, preventing build-time leakage.
- Clear naming and documentation: Variable names and comments make purpose and usage explicit, preventing misconfiguration.
This approach ensures secure and smooth configuration of environment variables for the TrustNet backend while easing setup for other developers.
{type}/{short-description}
feat/- New featuresfix/- Bug fixeshotfix/- Critical production fixesdocs/- Documentation updatesstyle/- Code style changes (formatting, etc.)refactor/- Code refactoringtest/- Adding testschore/- Maintenance tasks
feat/user-authenticationfix/login-validationdocs/api-endpointsrefactor/auth-system
- π New feature
- π Bug fix
- π Documentation
- π¨ Style update
- β»οΈ Code refactor
- β Test addition
- π§ Chore
-
β οΈ Breaking change
- My code follows the project style guidelines
- I have performed a self-review of my code
- I have commented my code where necessary
- I have updated the documentation if needed
- My changes generate no new warnings
- I have added tests that prove my fix is effective
- New and existing unit tests pass locally
This workflow helps because:
Code Quality:
- ESLint/Prettier catch issues early
- Code reviews catch bugs before merging
- Consistent patterns make code maintainable
Collaboration:
- Clear PR templates help reviewers understand changes
- Everyone follows same branching conventions
- CI/CD pipeline provides objective quality gates
Velocity:
- Automated checks save manual review time
- Clear processes reduce confusion and rework
- Quick feedback loops through CI pipeline
π§ Environment-Aware Build Setup
We created .env.development, .env.staging, and .env.production for each environment. Secrets are securely stored using GitHub Secrets and injected via CI/CD pipelines.
Build scripts:
npm run build:dev β Local testing
npm run build:staging β Staging deployment
npm run build:production β Production deployment
Why this matters: This setup ensures consistent deployments and protects sensitive credentials across environments. No real secrets are ever committed to GitHub.
This guide explains how to use Prisma ORM for database migrations and seed scripts to ensure all environments have a consistent database schema and initial data. It covers setup, migration management, seeding scripts, verifying data, and rollback safety.
- Ensure that Prisma and PostgreSQL are configured in your project.
- Initialize Prisma:
- npx prisma init
Generate migration files, apply them to the database, and update the Prisma Client:
- npx prisma migrate dev --name init_schema
To modify the schema or add a new table:
- npx prisma migrate dev --name add_project_table
Reset the database, re-apply all migrations, and optionally re-run the seed script:
- npx prisma migrate reset
- Create the file
prisma/seed.ts:
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient();
async function main() { await prisma.user.createMany({ data: [ { name: 'Alice', email: '[email protected]' }, { name: 'Bob', email: '[email protected]' }, ], }); console.log('Seed data inserted successfully'); }
main() .then(async () => await prisma.$disconnect()) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); });
- Add the seed command to your
package.json:
"prisma": { "seed": "ts-node prisma/seed.ts" }
- Run the seed script:
- npx prisma db seed
Use Prisma Studio to check that the seed data has been inserted:
- npx prisma studio
- Always test all migrations locally before applying to production.
- Use backups and staging environments for safety.
- Treat migrations as version-controlled code; do not edit existing migrations after theyβve been applied in production.
Our PostgreSQL schema enables core features:
User Management: Phone-based authentication with roles (Customer/Business Owner/Admin)
Business Profiles: Complete business info with trust scoring and multiple verification methods (phone, community, UPI)
Trust System: Reviews (1-5 stars), endorsements from community, and calculated trust scores
UPI Integration: Transaction pattern analysis without storing personal financial data
Analytics: Pre-computed metrics for fast dashboard performance
Privacy-first: Only aggregated UPI insights, no personal transaction data
Scalable design: CUID identifiers, proper indexing, cascade deletes
Multiple verification: Progressive trust building through different methods
Performance optimized: Indexed fields, efficient relationships
Quick Start
- npm run db:generate # Generate Prisma client
- npm run db:push # Update database schema
- npm run db:seed # Add sample data
- npm run db:studio # Database GUI
- The schema supports TrustNet's mission of building digital credibility for local businesses through community-powered verification.
All API responses in this project follow a consistent format to improve developer experience, debugging, and observability.
Example Success Response
{
"success": true,
"message": "User created successfully",
"data": { "id": 12, "name": "Charlie" },
"timestamp": "2025-11-07T10:00:00Z"
}Example Error Response
{
"success": false,
"message": "Missing required field: name",
"error": { "code": "VALIDATION_ERROR" },
"timestamp": "2025-11-07T10:00:00Z"
}βοΈ How the Dockerfile Works The Dockerfile defines how the TrustNet Next.js application is built, bundled, and run inside a lightweight containerized environment. Step-by-step breakdown: Base Image β
FROM node:20-alpine Uses a minimal Node.js 20 image for efficiency and security. The alpine variant ensures smaller image size and faster builds.
Working Directory Setup β
WORKDIR /app Sets /app as the directory inside the container where all files and commands will execute.
Dependency Installation β
COPY package*.json ./ RUN npm install Copies dependency files and installs them first, taking advantage of Docker layer caching β so dependencies arenβt reinstalled every build unless they change.
Project Build β
COPY . . RUN npm run build Copies the rest of the source code and builds the production-ready Next.js app.
Expose Port & Run App β
EXPOSE 3000 CMD ["npm", "run", "start"] Exposes port 3000 (the default Next.js port) and launches the app using the production build.
β Outcome: When built, this container runs the TrustNet app with all dependencies isolated β ready for deployment or local development.
π§± How the Docker Compose File Works The docker-compose.yml file orchestrates multiple containers β the app, PostgreSQL database, and Redis cache β to work together in one cohesive environment. Services Overview Service Purpose app Runs the Next.js frontend and backend (API routes). Connects to PostgreSQL and Redis using internal network aliases. db Hosts PostgreSQL database storing user, business, and trust score data. redis Provides caching and session management for faster analytics and authentication. Interconnection The depends_on field ensures the database and Redis containers start before the Next.js app begins running.
The environment section in the app container shares connection URLs for the database and Redis service.
Example: environment:
- DATABASE_URL=postgres://postgres:password@db:5432/mydb
- REDIS_URL=redis://redis:6379
Here, db and redis refer to service names, not IPs β Docker automatically resolves them through the shared network.
π Network Configuration The file defines a custom bridge network: networks: localnet: driver: bridge
All containers (app, db, redis) connect to localnet, allowing secure internal communication via service names: App β Database: postgres://postgres:password@db:5432/mydb
App β Redis: redis://redis:6379
Why this matters: It isolates containers from the host network, improving security and stability, while allowing seamless inter-service communication.
πΎ Volume Setup Persistent data is managed using Docker volumes: volumes: db_data:
The PostgreSQL service uses this volume: volumes:
- db_data:/var/lib/postgresql/data
This ensures: Database data persists across container restarts.
Developers can rebuild containers without losing local data.
The database remains isolated from the host file system, reducing risk of corruption.
π Environment Variable Sharing Environment variables are passed through the environment: section in docker-compose.yml.
Each container has its own set of environment variables β not visible outside its scope.
Sensitive data like DATABASE_URL and REDIS_URL are used internally (never exposed to the frontend).
For production and CI/CD, these values are replaced with secrets managed via AWS or Azure environment configuration.
Example: environment:
- NODE_ENV=production
- DATABASE_URL=${DATABASE_URL}
- REDIS_URL=${REDIS_URL}
(Using ${VARIABLE} allows automatic loading from a .env file.)
This project implements a centralized error handling system for Next.js applications that provides consistent error responses, structured logging, and environment-aware error details.
app/
βββ api/
β βββ users/
β β βββ route.ts
β βββ test/
β β βββ errors/route.ts
βββ lib/
β βββ logger.ts # Structured logging utility
β βββ errorHandler.ts # Centralized error handler
β βββ customErrors.ts # Custom error classes
- JSON-formatted logs for easy parsing
- Environment-aware stack trace handling
- Consistent log structure across all errors
AppError- Base error classValidationError- Input validation failures (400)NotFoundError- Resource not found (404)AuthenticationError- Auth failures (401)AuthorizationError- Permission issues (403)DatabaseError- Database operations (500)
{
"success": false,
"message": "User with ID 999 not found",
"error": {
"code": "NOT_FOUND"
},
"timestamp": "2025-10-30T10:00:00.000Z",
"stack": "Error: User with ID 999 not found at ..."
}{
"success": false,
"message": "User with ID 999 not found",
"error": {
"code": "NOT_FOUND"
},
"timestamp": "2025-10-30T10:00:00.000Z"
}
Visit these endpoints to test different error types:
-
/api/test/errors?type=validation - Validation error
-
/api/test/errors?type=not-found - Not found error
-
/api/test/errors?type=authentication - Authentication error
-
/api/test/errors?type=database - Database error
-
/api/test/errors?type=unknown - Generic error
app/ βββ api/ βββ auth/ β βββ register/ β β βββ route.ts β βββ login/ β β βββ route.ts β βββ verify-otp/ β βββ route.ts βββ users/ β βββ route.ts β βββ [id]/ β βββ route.ts βββ businesses/ β βββ route.ts β βββ [id]/ β βββ route.ts β βββ reviews/ β β βββ route.ts β βββ endorsements/ β β βββ route.ts β βββ analytics/ β βββ route.ts βββ reviews/ β βββ [id]/ β βββ route.ts βββ upi/ β βββ verify/ β β βββ route.ts β βββ transactions/ β βββ route.ts βββ search/ βββ route.ts
This project uses React Context API to manage global application state. Two major contexts are used:
-
AuthContext β Manages user authentication and session state.
-
UIContext β Manages global UI behavior such as sidebar toggling.
These contexts allow different parts of the app (Navbar, pages, components) to access shared state without prop drilling, improving scalability and maintainability.








