Core-X Backend Boilerplate ๐
โ ๏ธ Note: This project is currently in the active development phase.
๐ Overview
Core-X is not just another boilerplate; it is a production-ready backend foundation designed for developers who want to skip the repetitive setup of authentication, security, and logging.
Instead of writing a backend from scratch, Core-X provides a robust, secure, and scalable starting point. It integrates industry-standard security practices (CSRF, WAF, Rate Limiting) and a powerful authentication system powered by Supabase, allowing you to focus immediately on building your business logic.
โจ Why Core-X?
- ๐ก๏ธ Battle-Tested Security: Comes with a built-in Web Application Firewall (WAF) Lite, CSRF protection using "Double Submit Cooโฆ
Core-X Backend Boilerplate ๐
โ ๏ธ Note: This project is currently in the active development phase.
๐ Overview
Core-X is not just another boilerplate; it is a production-ready backend foundation designed for developers who want to skip the repetitive setup of authentication, security, and logging.
Instead of writing a backend from scratch, Core-X provides a robust, secure, and scalable starting point. It integrates industry-standard security practices (CSRF, WAF, Rate Limiting) and a powerful authentication system powered by Supabase, allowing you to focus immediately on building your business logic.
โจ Why Core-X?
- ๐ก๏ธ Battle-Tested Security: Comes with a built-in Web Application Firewall (WAF) Lite, CSRF protection using "Double Submit Cookie", and strict Helmet headers.
- ๐ Supabase Integration: Pre-configured authentication middleware supporting both Cloud verification and highly optimized Local JWT verification.
- โก Multi-Core Scalability: Built-in Cluster support that automatically utilizes all available CPU cores for maximum performance.
- ๐ Advanced Logging: Centralized Winston logger with daily file rotation and separate security threat logs.
- โ Strict Validation: Integrated Zod validation with automatic deep security scanning for malicious payloads (SQLi, XSS).
๐ ๏ธ Tech Stack
- Runtime: Node.js (ES Modules)
- Framework: Express.js
- Database & Auth: Supabase (PostgreSQL)
- Validation: Zod
- Security: Helmet, HPP, CSURF (Custom Implementation), Express-Rate-Limit
- Logging: Winston & Winston-Daily-Rotate-File
๐ Project Structure
core-x/
โโโ logs/
โโโ src/
โ โโโ config/
โ โ โโโ logger.js
โ โ โโโ supabase.js
โ โโโ constants/
โ โ โโโ responseCodes.js
โ โ โโโ securityPatterns.js
โ โ โโโ validationMessages.js
โ โโโ controllers/ # (Coming Soon)
โ โโโ db/ # (Coming Soon)
โ โโโ middleware/
โ โ โโโ auth.middleware.js
โ โ โโโ csrf.middleware.js
โ โ โโโ security.middleware.js
โ โ โโโ validate.js
โ โโโ routes/ # (Coming Soon)
โ โโโ services/ # (Coming Soon)
โ โโโ utils/
โ โ โโโ responseHandler.js
โ โ โโโ securityValidator.js
โ โโโ validations/
โ โ โโโ common.js
โ โโโ app.js
โ โโโ server.js
โโโ tests/
โ โโโ logger.test.js
โ โโโ responses.test.js
โ โโโ security.test.js
โโโ .env
โโโ .env.example
โโโ .gitignore
โโโ index.js
โโโ LICENSE
โโโ package-lock.json
โโโ package.json
โโโ README.md
๐ Getting Started
1. Prerequisites
- Node.js (v18 or higher)
- Supabase Account (for URL and Keys)
2. Installation
Clone the repository and install dependencies:
git clone https://github.com/your-repo/core-x.git
cd core-x
npm install
3. Configuration
Create a .env file in the root directory:
PORT=5000
# =============================================================================
# ๐ชต Logger Configuration
# =============================================================================
NODE_ENV=development # development | production
SERVICE_NAME=Core-X-Backend
LOG_LEVEL=debug # debug | http | info | warn | error
ENABLE_CONSOLE_LOGS=false # Force console logs in production if true
# =============================================================================
# โก Supabase Configuration
# =============================================================================
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
SUPABASE_ANON_KEY=your-anon-key # Optional for backend, but good to have
TEST_SUPABASE_ON_START=true
# =============================================================================
# ๐ Security Configuration
# =============================================================================
# Generate a strong secret by running this in terminal:
# node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
COOKIE_SECRET=super_secure_random_string_at_least_32_chars
# SUPABASE_JWT_SECRET=your-jwt-secret (Optional for Local Verification)
CORS_ORIGINS=http://localhost:3000,http://localhost:5173
4. Run Locally
# Development Mode (Console Logs + Hot Reload)
npm run dev
# Production Mode (File Logs + Cluster Optimization)
npm start
๐ Frontend Integration Guide
Since Core-X uses stateless CSRF protection, your frontend client (React, Vue, etc.) must include the CSRF token in the headers of mutative requests (POST, PUT, DELETE).
Using Axios?
Itโs handled automatically if configured correctly:
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:5000',
withCredentials: true, // IMPORTANT: Allows cookies to be sent/received
xsrfCookieName: 'csrf_token', // The name of the cookie sent by Core-X
xsrfHeaderName: 'X-CSRF-Token', // The header Core-X expects
});
export default api;
How the handshake works:
- On the first visit, make a GET request (e.g., to
/api/healthor/auth/me). - Core-X will set the
csrf_tokencookie. - Axios reads this cookie and attaches it to the
X-CSRF-Tokenheader for all subsequent requests.
๐ก API Response Structure
Core-X enforces a strict, unified JSON response format for all endpoints, ensuring the frontend always knows what to expect.
Success Response (200 OK)
{
"success": true,
"code": 200,
"slug": "LOGIN_SUCCESS",
"message": "Logged in successfully.",
"data": {
"user": { "id": "123", "email": "dev@example.com" },
},
"meta": {
"requestId": "req_a1b2c3d4",
"timestamp": "2026-01-19T12:00:00.000Z"
}
}
Operational Error (401 Unauthorized)
{
"success": false,
"code": 401,
"slug": "INVALID_CREDENTIALS",
"message": "Invalid email or password.",
"data": null,
"meta": {
"requestId": "req_992100",
"timestamp": "2026-01-19T10:35:00.000Z"
}
}
System Error (500 - Development Mode Only)
Includes a debug field with stack traces to help developers fix issues fast.
{
"success": false,
"code": 500,
"slug": "DB_CONNECTION_ERROR",
"message": "Internal Server Error",
"data": null,
"meta": {
"requestId": "req_555123",
"timestamp": "2026-01-19T10:40:00.000Z"
},
"debug": {
"error_message": "Connection to Supabase timed out",
"stack": "Error: Connection to Supabase timed out\n at Client.connect (/app/node_modules/pg/lib/client.js:52)...",
"raw": {
"errno": -110,
"code": "ETIMEDOUT",
"syscall": "connect"
}
}
}
๐ก๏ธ Security Features Details
| Feature | Description |
|---|---|
| Double Submit Cookie | Protects against CSRF by requiring a token in both the cookie and the header. |
| WAF Lite | Blocks known malicious User-Agents (scanners like SQLMap, Nessus) instantly. |
| Deep Input Scan | Recursively scans all incoming JSON bodies for SQL Injection, XSS, and Prototype Pollution attacks. |
| Secure Headers | Implements HSTS, CSP, NoSniff, and Frameguard via Helmet. |
| Rate Limiting | Limits requests to 200 per 15 minutes per IP to prevent Brute Force / DDoS. |
๐ Advanced Logging System
Core-X eschews standard console logging in production for a robust, persistent file-based system powered by Winston.
๐ Log Structure (/logs)
combined-%DATE%.log: Records all server activity (Request paths, Response times, Info messages). Good for general debugging.error-%DATE%.log: Strictly records errors and stack traces. Check this first when something breaks.security/threats-%DATE%.log: ๐จ The Alert Channel. Only contains confirmed security threats (like SQL Injection attempts).
Rotation Policy: Logs are automatically rotated daily and kept for 14 days (Combined) or 30 days (Errors/Security) to manage disk space efficiently.
๐ชค Threat Detection Engine (The "Trap")
Core-X doesnโt just block attacks; it identifies and logs them using a custom engine (SecurityValidator.js) that acts as a trap for malicious actors.
How it works:
- Perimeter Scan: The
security.middlewarefirst checks the visitorโs User-Agent. Known scanning tools (like SQLMap, Nessus, Burp Suite) are instantly blocked before they can touch your API. - Deep Payload Inspection: Every time data is sent to your API (via
req.body,query, orparams), it passes through the Zod Validation Layer. - The Trap: Inside Zod, a custom
.refine()rule runs theSecurityValidator.scan(). It looks for:
- ๐ SQL Injection (
UNION SELECT,OR 1=1) - ๐ XSS Scripts (
<script>,javascript:) - ๐ Path Traversal (
../../etc/passwd)
- Reaction: If a threat is detected:
- The request is terminated immediately (403 Forbidden).
- The user receives a generic "Security Policy Violation" message (Security by Obscurity).
- Crucially, the system logs the incident to
logs/security/threats-*.logwith the Attackerโs IP, the malicious payload, and the threat type.
This allows you to passively monitor who is trying to hack your application without risking your data.
๐ Internationalization (i18n) Ready
Core-X is designed from the ground up to support multi-language applications without cluttering the backend with translation logic.
The Strategy:
Instead of sending hardcoded text (which forces the backend to know the userโs language), the API returns a dual-layer response:
The slug (Primary Layer):
- A stable, machine-readable string code (e.g.,
"INVALID_CREDENTIALS"). - Frontend Role: The frontend receives this slug and uses it as a key to look up the correct translation from its own language files (e.g.,
en.json,ar.json). - Example:
slug: "LOGIN_SUCCESS"โ Frontend looks up key and displays "ุชู ุชุณุฌูู ุงูุฏุฎูู ุจูุฌุงุญ" (if Arabic is selected).
The message (Fallback Layer):
- A default English string provided by the server.
- Purpose: Acts as a safety net. If the frontend forgets to define a translation for a specific slug, or if a new error code is introduced, this message can be displayed directly to the user so they arenโt left with an empty screen.
๐ค Contributing
This project is intended to be a community-driven starting point. Pull requests are welcome!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
๐ฌ Contact
Have questions or want to collaborate? Iโd love to hear from you!
- linktr.ee: Connect with me
Built with โค๏ธ for Developers by [Ymzerotwo]