### MareJS Project Creation and Development Server Source: https://github.com/emadklenka/marejs/blob/main/README.md Commands to create a new MareJS project using npx, install dependencies, and start the development server. Assumes npx and npm are installed. ```bash npx github:/emadklenka/marejs my-app cd my-app npm install npm run dev ``` -------------------------------- ### MareJS Development Server Setup (Bash) Source: https://context7.com/emadklenka/marejs/llms.txt Commands to set up and run the MareJS framework in development mode. Includes installing dependencies and starting the server with hot reload for both frontend and backend, utilizing tools like `npm` and `nodemon`. ```bash # Install dependencies npm install # Start both frontend and backend with hot reload npm run dev # Server starts at http://localhost:4000 # Frontend: Vite dev server with HMR # Backend: Nodemon watching API changes ``` -------------------------------- ### Create and Run a MareJS App Source: https://github.com/emadklenka/marejs/blob/main/README.md This snippet demonstrates how to create a new MareJS project using npx, navigate into the project directory, and start the development server. It's the initial setup for any new MareJS application. ```bash npx github:/emadklenka/marejs my-app cd my-app npm run dev ``` -------------------------------- ### MareJS Build and Start Commands Source: https://github.com/emadklenka/marejs/blob/main/README.md Provides the command-line instructions for building a MareJS application for production and starting the production server. `npm run build` creates the production-ready assets, and `npm start` launches the application on `http://localhost:4000`. ```bash npm run build ``` ```bash npm start ``` -------------------------------- ### Server Startup Configuration with JavaScript Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt The `server_startup.js` file allows for pre-server initialization tasks such as database connections, cache warming, and configuration loading. The `Server_Startup` function must return `true` for the server to start; otherwise, it will fail. ```javascript export async function Server_Startup() { try { // Connect to database await connectDatabase(); // Load cache await warmupCache(); // Your initialization code here return true; // Success } catch (error) { console.error('Startup failed:', error); return false; // Failure (server won't start) } } ``` -------------------------------- ### MareJS Production Build and Deployment (Bash) Source: https://context7.com/emadklenka/marejs/llms.txt Instructions for building the MareJS application for production and starting the production server. Covers using `npm start`, `pm2` for process management, and Docker for containerized deployment. ```bash # Build frontend and backend npm run build # Start production server npm start # Or using PM2 for process management pm2 start .mareJS/mare_server.js --name marejs-app # Using Docker docker build -t my-marejs-app . docker run -p 4000:4000 my-marejs-app ``` -------------------------------- ### Backend API Endpoint Example (Node.js/Express) Source: https://github.com/emadklenka/marejs/blob/main/PROMPT.md An example of a dynamic backend API endpoint in MareJS. This handler is automatically mapped to a specific route based on its file location within the 'api/' directory. It demonstrates how to access dynamic route parameters from the request object and send a JSON response. ```javascript // api/user/[id].js export default async function handler(req, res) { res.json({ id: req.params.id }); } ``` -------------------------------- ### Implementing Server Startup Logic Source: https://context7.com/emadklenka/marejs/llms.txt Details how to implement logic that runs before the server starts, such as initializing databases, warming up caches, and establishing connections to external services. ```APIDOC ## Configuration /api/__mare_serversettings/server_startup.js ### Description Defines asynchronous logic to be executed during server startup, including database connections, cache preloading, and initialization of external services. ### Method N/A (Configuration file) ### Endpoint N/A (Configuration file: `/api/__mare_serversettings/server_startup.js`) ### Parameters None ### Request Example N/A ### Response N/A ### Usage Notes - The `Server_Startup` function must return `true` for the server to start successfully. - Returns `false` if any initialization step fails, preventing server startup. - Relies on environment variables for database connection details (e.g., `DB_HOST`, `DB_PORT`, `DB_NAME`). ``` -------------------------------- ### Frontend Page Layout Example (React) Source: https://github.com/emadklenka/marejs/blob/main/PROMPT.md Demonstrates how to create a folder-based layout for frontend routes in MareJS. The 'layout.jsx' file automatically wraps child pages within its structure, providing a consistent UI for a route segment. It accepts children and other props passed down from the routing system. ```jsx // pages/news/layout.jsx export default function LayoutNews({ children, id }) { return (
News Layout {id}
{children}
); } ``` -------------------------------- ### Environment Variables Configuration (.env) Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt Environment variables can be defined in the `.env` file and accessed via `process.env`. This example shows how to enable safe routes and configure WAF mode. ```plaintext WAF_SAFE_ROUTES=true Enable safe routes config WAF_STRICT=false Ignore safe routes entirely ``` ```plaintext WAF=true WAF_MODE=block ``` -------------------------------- ### API Endpoint - Dynamic Route Source: https://github.com/emadklenka/marejs/blob/main/README.md Example of creating a dynamic API endpoint that accepts a parameter in the URL. ```APIDOC ## GET /api/user/[id] ### Description Fetches user data based on the provided user ID. ### Method GET ### Endpoint `/api/user/:id` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **id** (string) - The user's unique identifier. - **name** (string) - The user's name. #### Response Example ```json { "id": "123", "name": "User 123" } ``` ``` -------------------------------- ### Creating a Public API Route in JavaScript Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt This example shows how to create a public API route that does not require authentication. It follows the same pattern as a standard route, but is placed in the `api/public/` directory. ```javascript export default (req, res) => { res.json({ status: 'OK' }); }; ``` -------------------------------- ### Implement Server Startup Logic in JavaScript Source: https://context7.com/emadklenka/marejs/llms.txt Handles server initialization logic, including database connections, cache warming, and external service integrations before the server starts. It uses environment variables for configuration and returns a boolean indicating success or failure. ```javascript // api/__mare_serversettings/server_startup.js export async function Server_Startup() { try { // Database initialization const db = await connectToDatabase({ host: process.env.DB_HOST, port: process.env.DB_PORT, database: process.env.DB_NAME }); // Cache warmup await warmupCache(); // External service connections await initializePaymentGateway(); console.log('✅ All services initialized successfully'); return true; } catch (error) { console.error('❌ Server startup failed:', error); return false; // Server won't start if this returns false } } async function connectToDatabase(config) { // Your database connection logic console.log('Database connected'); return { connected: true }; } async function warmupCache() { // Preload frequently accessed data console.log('Cache warmed up'); } async function initializePaymentGateway() { // Initialize Stripe, PayPal, etc. console.log('Payment gateway initialized'); } ``` -------------------------------- ### WAF Attack Examples with Curl (Bash) Source: https://context7.com/emadklenka/marejs/llms.txt These examples show how to simulate different types of web attacks (XSS, SQL Injection, Path Traversal) using `curl` commands to test the MareJS WAF's blocking capabilities. They illustrate the request format and the expected 403 Forbidden response. ```bash # XSS Attack Example curl -X POST http://localhost:4000/api/comments \ -H "Content-Type: application/json" \ -d '{"text":""}' # Response: 403 Forbidden - "Request blocked by Web Application Firewall" # SQL Injection Example curl "http://localhost:4000/api/users?id=' OR 1=1--" # Response: 403 Forbidden - Threat type: "SQL Injection" # Path Traversal Example curl "http://localhost:4000/api/files?path=../../etc/passwd" # Response: 403 Forbidden - Threat type: "Path Traversal" ``` -------------------------------- ### Creating Dynamic API Routes Source: https://context7.com/emadklenka/marejs/llms.txt Illustrates how to create dynamic API routes that can capture parameters from the URL, such as user IDs. The example shows fetching user data based on an ID. ```APIDOC ## GET /api/users/[id] ### Description Creates a dynamic API endpoint that extracts parameters from the URL, such as a user ID, to fetch specific data. ### Method GET ### Endpoint `/api/users/[id]` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier for the user. #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:4000/api/users/123 ``` ### Response #### Success Response (200) - **id** (string) - The user's ID. - **name** (string) - The user's name. - **email** (string) - The user's email address. #### Response Example ```json { "id": "123", "name": "User 123", "email": "user123@example.com" } ``` ``` -------------------------------- ### Configuring CORS Settings Source: https://context7.com/emadklenka/marejs/llms.txt Provides guidance on configuring Cross-Origin Resource Sharing (CORS) settings for your API. It includes examples for production and development environments. ```APIDOC ## Configuration /api/__mare_serversettings/cors.js ### Description Configures Cross-Origin Resource Sharing (CORS) settings for the API, allowing control over which domains can access the resources. ### Method N/A (Configuration file) ### Endpoint N/A (Configuration file: `/api/__mare_serversettings/cors.js`) ### Parameters None ### Request Example N/A ### Response N/A ### Usage Notes - **Production:** Restrict origins to specific domains (e.g., `https://yourdomain.com`). - **Development:** Can allow all origins (`origin: true`) for easier local testing. ``` -------------------------------- ### Running Automated WAF Tests Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt The `waftest.js` script in the `tests/` directory is used to run automated security tests against the WAF. Tests can be executed directly or against a different server URL using an environment variable. ```bash node tests/waftest.js ``` ```bash TEST_URL=http://localhost:3002 node tests/waftest.js ``` -------------------------------- ### Configure Server Port and Environment Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt This snippet shows environment variables for basic server configuration. `PORT` defines the port the server listens on, with a default of 4000. `NODE_ENV` specifies the operating environment, typically 'development' or 'production', which can affect application behavior and logging. ```env PORT=4000 NODE_ENV=development ``` -------------------------------- ### Creating a New API Route in JavaScript Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt This snippet demonstrates how to create a basic API route. The default export is a function that receives request (`req`) and response (`res`) objects. The route is accessible via HTTP. ```javascript export default (req, res) => { res.json({ message: 'Hello!' }); }; ``` -------------------------------- ### Nested Dynamic Route Component in MareJS Source: https://github.com/emadklenka/marejs/blob/main/README.md Demonstrates creating nested dynamic routes in MareJS using square brackets in filenames. This example (`pages/blog/[slug]/page.jsx`) creates a route structure where a slug is nested within a blog directory, allowing for specific blog post pages. ```jsx // pages/blog/[slug]/page.jsx export default function BlogPost({ slug }) { return

Blog Post: {slug}

; } ``` -------------------------------- ### Using Dynamic Parameters in API Routes (JavaScript) Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt This snippet illustrates how to create API routes with dynamic URL parameters. The parameter is accessed via `req.params`. ```javascript export default (req, res) => { res.json({ userId: req.params.id }); }; ``` -------------------------------- ### MareJS User Profile Dynamic Route Source: https://github.com/emadklenka/marejs/blob/main/README.md An example of a dynamic user profile page using MareJS. The filename `pages/user/[id].jsx` defines a route parameter `id`. The component receives this `id` as a prop and displays a user profile title, demonstrating how to access dynamic URL segments. ```jsx import React from 'react'; export default function UserProfile({ id }) { return

User Profile for User ID: {id}

; } ``` -------------------------------- ### Create Shared Layouts in React (JSX) Source: https://context7.com/emadklenka/marejs/llms.txt Builds reusable layouts for consistent UI design in a React application. This example demonstrates a main layout component with a navigation bar and footer, which can wrap other page content. It utilizes React Router for navigation links. ```jsx // src/_MainLayout.jsx import { Link } from 'react-router-dom'; export default function MainLayout({ children }) { return (
{children}
); } ``` -------------------------------- ### MareJS API Endpoint for User Data Source: https://github.com/emadklenka/marejs/blob/main/README.md An example of a dynamic API endpoint in MareJS for fetching user data. The filename `api/user/[id].js` indicates a dynamic parameter `id` which is extracted from `req.params`. The handler function then uses this `id` to retrieve and return user data. ```javascript export default async function handler(req, res) { const { id } = req.params; // Fetch user data based on ID const userData = await getUserData(id); res.json(userData); } async function getUserData(id) { // Mock data for demonstration return { id, name: `User ${id}` }; } ``` -------------------------------- ### Multiple Dynamic Route Parameters - JavaScript Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt Demonstrates the capability of MareJS to handle multiple dynamic parameters within a single route. By nesting folders with bracket notation, you can capture multiple segments of the URL, making it possible to create deeply nested and parameter-driven API endpoints. ```javascript // api/posts/[postId]/comments/[commentId].js // Access via: req.params.postId and req.params.commentId ``` -------------------------------- ### Basic API Route Handler - JavaScript Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt Defines a basic API route handler in JavaScript using MareJS. It exports a default function that accepts request and response objects and sends a JSON response. This is the fundamental structure for creating API endpoints. ```javascript // api/hello.js export default (req, res) => { res.json({ message: 'Hello World!' }); }; ``` -------------------------------- ### Create Dynamic API Route with Parameter in JavaScript Source: https://context7.com/emadklenka/marejs/llms.txt Implements a dynamic API endpoint that extracts parameters from the request URL. It uses `req.params` to get the `id` and simulates fetching user data, returning it as JSON. Includes error handling for API requests. ```javascript // api/users/[id].js export default async function handler(req, res) { const { id } = req.params; try { // Fetch user data based on ID const userData = await getUserData(id); res.json(userData); } catch (error) { console.error('API Error:', error); res.status(500).json({ error: error.message }); } } async function getUserData(id) { // Your database query here return { id, name: `User ${id}`, email: `user${id}@example.com` }; } ``` -------------------------------- ### WAF Security Response Example Source: https://github.com/emadklenka/marejs/blob/main/README.md MareJS includes a built-in Web Application Firewall (WAF) that automatically protects against common threats like SQL injection. When an attack is detected, MareJS returns a '403 Forbidden' response, detailing the type of threat and the parameter involved, ensuring security without developer intervention. ```json { "error": "Forbidden", "message": "Request blocked by Web Application Firewall", "threats": [{ "type": "SQL Injection", "parameter": "query.id" }] } ``` -------------------------------- ### WAF Blocked Attack Log Format Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt This shows the format of logs generated when the Web Application Firewall (WAF) blocks a malicious request. It includes timestamps, IP address, the path of the request, the type of attack detected, and the specific parameter and value that triggered the block. ```log [WAF BLOCKED] 2025-10-24 14:32:15 | IP: 127.0.0.1 | Path: /api/user | Attack: XSS | Param: query.name | Value: ``` -------------------------------- ### API Route Handler Using Index File - JavaScript Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt Demonstrates how to use an index.js file within a folder to define an API route in MareJS. This pattern allows for cleaner organization of routes, especially when dealing with nested structures. It exports a default function similar to standalone route files. ```javascript // api/hello/index.js export default (req, res) => { res.json({ message: 'Hello from index!' }); }; // This responds to: /api/hello ``` -------------------------------- ### Configure Safe Routes for WAF Bypasses Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt This JavaScript configuration file (`saferoutes.config.js`) defines routes that should bypass the Web Application Firewall (WAF). It supports exact path matching, pattern-based wildcards, and partial bypasses for specific HTTP methods or checks. This is useful for webhooks or other routes that may intentionally trigger WAF rules. ```javascript export default { // Completely bypass WAF for exact paths exact: [ "/api/public/webhooks/github", "/api/public/webhooks/stripe" ], // Pattern-based bypasses (wildcards) patterns: [ "/api/public/webhooks/*" ], // Partial bypasses (disable specific checks only) partial: [ { path: "/api/blog/post", methods: ["POST", "PUT"], skip: ["xss"], reason: "Blog posts contain legitimate HTML" } ] }; ``` -------------------------------- ### Configure WAF Modes via Environment Variables Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt This snippet shows how to configure the Web Application Firewall (WAF) modes using environment variables. These variables control the WAF's behavior, from blocking malicious requests to logging them or disabling the WAF entirely. The default mode is 'block'. ```env WAF_MODE=block # or WAF_MODE=log # or WAF=false WAF_MODE=off ``` -------------------------------- ### WAF Blocked Response Payload Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt When the Web Application Firewall (WAF) blocks a request, it returns a JSON response to the attacker. This response includes a 'Forbidden' status (HTTP 403), an error message, and details about the detected threats, including their type and the parameter they were found in. ```json { "error": "Forbidden", "message": "Request blocked by Web Application Firewall", "threats": [ { "type": "XSS", "parameter": "query.name" } ] } ``` -------------------------------- ### Accessing Request Data in MareJS - JavaScript Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt Illustrates how to access various parts of the incoming request object within a MareJS route handler. It shows how to retrieve query parameters, request body, route parameters, and session data, providing flexibility in handling different types of client requests. ```javascript export default (req, res) => { const queryParams = req.query; // GET: ?name=value const bodyData = req.body; // POST: JSON body const routeParams = req.params; // Dynamic: /api/user/:id const session = req.session; // Session data res.json({ success: true }); }; ``` -------------------------------- ### Dynamic Route Parameter Handling - JavaScript Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt Shows how to define and access dynamic route parameters in MareJS using bracket notation in folder names (e.g., [id]). The parameter value is then available in the `req.params` object within the route handler, enabling personalized API responses based on URL segments. ```javascript // api/users/[id]/index.js export default (req, res) => { const userId = req.params.id; res.json({ userId: userId }); }; // Request: // GET /api/users/123 // Response: // { "userId": "123" } ``` -------------------------------- ### Disable WAF Completely or Use Log Only Mode Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt This snippet demonstrates two methods for disabling or altering the behavior of the Web Application Firewall (WAF). You can completely disable it by setting `WAF=false` in your `.env` file, or you can switch to 'log only' mode by setting `WAF_MODE=log`, which logs attacks without blocking requests. ```env WAF=false # or WAF_MODE=log ``` -------------------------------- ### Disable Safe Routes or Enable Strict Mode for WAF Source: https://github.com/emadklenka/marejs/blob/main/docs/serverside.txt These environment variables control how the Web Application Firewall (WAF) handles safe routes. Setting `WAF_SAFE_ROUTES=false` will cause the WAF to ignore the `saferoutes.config.js` file entirely. Alternatively, `WAF_STRICT=true` forces the WAF to check all routes regardless of the safe routes configuration. ```env WAF_SAFE_ROUTES=false # or WAF_STRICT=true ``` -------------------------------- ### Server Startup Configuration Source: https://github.com/emadklenka/marejs/blob/main/README.md Details the `Server_Startup` function used for initializing server-side resources before the application begins. ```APIDOC ## Server Startup Function ### Description Defines a function that executes during server initialization, allowing for setup tasks like database connections or cache configurations. ### Method N/A (Initialization Function) ### Endpoint N/A (Defined in `server_startup.js`) ### Parameters N/A ### Request Example ```javascript // server_startup.js export async function Server_Startup() { try { console.log('Starting server initialization...'); // Example: Initialize database connection // await connectToDatabase(); // Example: Setup cache // setupCache(); console.log('Server initialization successful.'); return true; } catch (error) { console.error('Server startup failed:', error); return false; } } ``` ### Response - **boolean** - Returns `true` if startup is successful, `false` otherwise. ``` -------------------------------- ### Server Startup Logic in JavaScript Source: https://github.com/emadklenka/marejs/blob/main/README.md Provides a function `Server_Startup` that executes before the server begins its main operations. This is intended for initialization tasks like setting up databases or caches. It returns a boolean indicating success or failure and logs errors if startup fails. ```javascript export async function Server_Startup() { try { // Initialize databases, caches, etc. return true; } catch (error) { console.error('Startup failed:', error); return false; } } ``` -------------------------------- ### MareJS Root and Main Layout Components Source: https://github.com/emadklenka/marejs/blob/main/README.md Illustrates the layout system in MareJS using `_app.jsx` as the root component and `_MainLayout.jsx` for main navigation. `_app.jsx` wraps all pages within `MainLayout`, which includes navigation and a main content area for the children. ```jsx // _app.jsx - Root layout import MainLayout from './_MainLayout'; export default function App() { return ( {/* Page content goes here */} ); } ``` ```jsx // _MainLayout.jsx - Main navigation export default function MainLayout({ children }) { return ( <>
{children}
); } ``` -------------------------------- ### MareJS Project Structure Overview Source: https://github.com/emadklenka/marejs/blob/main/README.md Illustrates the typical directory structure of a MareJS project, highlighting key folders for frontend pages, backend APIs, configuration, and framework internals. ```plaintext my-app/ ├── pages/ 📄 Frontend Routes (React/JSX) │ ├── index.jsx → / (home page) │ ├── about.jsx → /about │ ├── blog/ │ │ └── [slug].jsx → /blog/my-post (dynamic) │ ├── _app.jsx → Root layout wrapper │ └── _MainLayout.jsx → Navigation layout │ ├── api/ 🔌 Backend Routes (Express) │ ├── hello.js → /api/hello │ ├── hello/ │ │ └── index.js → /api/hello (folder-based) │ ├── users/ │ │ └── [id].js → /api/users/123 (dynamic) │ ├── public/ → 🌍 Public routes (no auth) │ │ └── webhook.js → /api/public/webhook │ └── __mare_serversettings/ │ ├── server_startup.js Server initialization │ ├── session.js Session config │ ├── cors.js CORS config │ └── middleware.js Auth middleware │ ├── tests/ 🧪 Test Suite │ └── waftest.js → WAF security tests │ ├── docs/ 📚 Documentation │ └── serverside.txt → Complete backend guide │ ├── .mareJS/ ⚙️ Framework Core (DON'T EDIT) │ ├── mare_server.js → Main server │ └── waf/ │ ├── waf.js → WAF middleware │ ├── xss.js → XSS detection │ ├── sqli.js → SQL injection detection │ └── pathtraversal.js → Path traversal detection │ ├── public/ 🎨 Static Assets │ └── assets/ │ ├── saferoutes.config.js 🛡️ WAF bypass rules (optional) ├── .env 🔐 Environment variables └── package.json ``` -------------------------------- ### API Endpoint - Middleware Chain Source: https://github.com/emadklenka/marejs/blob/main/README.md Demonstrates how to create an API endpoint that utilizes a chain of middleware for request validation and authentication before processing. ```APIDOC ## POST /api/data ### Description Processes data after validating the request and authenticating the user. ### Method POST ### Endpoint `/api/data` ### Parameters #### Request Body (Assumed to contain necessary data for `getData` function) ### Request Example ```json { "someData": "example" } ``` ### Response #### Success Response (200) - **data** - The data returned by the `getData` function. #### Response Example ```json { "data": "processed data" } ``` ### Notes This endpoint relies on `validateRequest` and `authenticate` middleware, and potentially other internal logic (`getData`). It returns a 400 error if the request is invalid, and a 401 error if authentication fails. ``` -------------------------------- ### Custom Middleware Implementation Source: https://github.com/emadklenka/marejs/blob/main/README.md Shows how to create and register custom middleware functions to extend API request processing. ```APIDOC ## Middleware Registration ### Description Allows developers to define and integrate custom middleware functions into the API request pipeline. ### Method N/A (Configuration) ### Endpoint N/A (Configuration within `mare_server.js`) ### Parameters #### Request Body N/A ### Request Example (Middleware Definition) ```javascript // api/__mare_serversettings/custom-middleware.js export default function customMiddleware(req, res, next) { // Your middleware logic here console.log('Custom middleware executed'); next(); // Call next() to pass control to the next middleware or route handler } ``` ### Request Example (Registration) ```javascript // mare_server.js import express from 'express'; import customMiddleware from './api/__mare_serversettings/custom-middleware.js'; const app = express(); // Register custom middleware app.use(customMiddleware); // Other middleware and routes... // ... server setup ... ``` ### Response N/A (Middleware modifies request/response flow) ### Notes Custom middleware functions should accept `req`, `res`, and `next` as arguments. Ensure `next()` is called to proceed unless the middleware intends to terminate the request. ``` -------------------------------- ### Implement WebSocket Chat Handler in MareJS Source: https://github.com/emadklenka/marejs/blob/main/README.md This JavaScript code defines a WebSocket handler for a chat feature within a MareJS application. It demonstrates how to set up a handler, send welcome messages, receive and process incoming messages, broadcast messages to clients, and handle client disconnections. This functionality is typically placed in the `api/wss/` directory. ```javascript // api/wss/chat.js export default function chatHandler(ws, req) { console.log('🔌 Chat client connected'); // Send welcome message ws.send(JSON.stringify({ type: 'welcome', message: 'Welcome to the chat!' })); // Handle incoming messages ws.on('message', (data) => { const message = JSON.parse(data.toString()); console.log('📨 Received:', message); // Broadcast to all clients (implement your logic) ws.send(JSON.stringify({ type: 'message', user: message.user, text: message.text, timestamp: new Date().toISOString() })); }); // Handle disconnection ws.on('close', () => { console.log('🔌 Chat client disconnected'); }); } ``` -------------------------------- ### Create React Pages with File-Based Routing (JSX) Source: https://context7.com/emadklenka/marejs/llms.txt Demonstrates creating frontend pages using React components with file-based routing. No explicit router configuration is needed; pages are automatically routed based on their file location. This snippet shows a simple 'About' page. ```jsx // src/pages/about.jsx export default function About() { return (

About Us

This page was automatically routed to /about

); } ``` -------------------------------- ### Create Dynamic Frontend Routes (React & JavaScript) Source: https://context7.com/emadklenka/marejs/llms.txt Builds dynamic frontend pages that accept URL parameters using React and React Router's hooks. It fetches data based on a dynamic slug and renders the content. A matching API endpoint for fetching blog posts is also provided. ```jsx // src/pages/blog/[slug]/page.jsx import { useParams } from 'react-router-dom'; import { useState, useEffect } from 'react'; export default function BlogPost() { const { slug } = useParams(); const [post, setPost] = useState(null); useEffect(() => { fetch(`/api/blog/${slug}`) .then(res => res.json()) .then(data => setPost(data)) .catch(error => console.error('Error loading post:', error)); }, [slug]); if (!post) return
Loading...
; return (

{post.title}

); } ``` ```javascript // api/blog/[slug].js export default async function handler(req, res) { const { slug } = req.params; const post = await getBlogPost(slug); res.json(post); } ``` -------------------------------- ### MareJS API Endpoint with Middleware Chain Source: https://github.com/emadklenka/marejs/blob/main/README.md Illustrates an advanced MareJS API endpoint that implements a middleware chain. It includes request validation and user authentication steps before processing the main request to fetch data. Error handling for each step is demonstrated. ```javascript export default async function handler(req, res) { // First middleware if (!validateRequest(req)) { return res.status(400).json({ error: 'Invalid request' }); } // Second middleware const user = await authenticate(req); if (!user) { return res.status(401).end(); } // Main handler res.json({ data: await getData(user) }); } ``` -------------------------------- ### Frontend File-Based Routing with React Source: https://github.com/emadklenka/marejs/blob/main/README.md MareJS enables Next.js-like file-based routing for React applications. Developers can create components in the 'pages' directory, and MareJS automatically maps them to URL routes. Layouts can be defined in '_MainLayout.jsx' to provide shared UI elements across pages. Dynamic routes are supported using bracket notation, like '[slug]'. ```jsx export default function Home() { return

Welcome to MareJS!

; } ``` ```jsx export default function BlogPost({ slug }) { return
Blog post: {slug}
; } ``` ```jsx export default function MainLayout({ children }) { return ( <>
{children}
); } ``` -------------------------------- ### Backend File-Based API Routing Source: https://github.com/emadklenka/marejs/blob/main/README.md MareJS supports file-based API routing in the 'api' directory. Similar to frontend routing, files are automatically mapped to API endpoints. Dynamic API routes can be created using bracket notation. Routes in 'api/public/*' are publicly accessible, while others require authentication. ```javascript export default (req, res) => { res.json({ message: 'Hello World!' }); }; ``` ```javascript export default (req, res) => { const { id } = req.params; res.json({ userId: id }); }; ``` ```javascript export default (req, res) => { res.json({ status: 'ok' }); }; ``` -------------------------------- ### Using Static Assets in MareJS Source: https://github.com/emadklenka/marejs/blob/main/README.md Shows how to reference static assets within a MareJS application. Files placed in the `public` directory (e.g., `public/assets/logo.png`) are directly accessible via their relative path from the root of the application (e.g., `/assets/logo.png`). ```jsx Logo ``` -------------------------------- ### Managing Session Configuration Source: https://context7.com/emadklenka/marejs/llms.txt Explains how to configure Express sessions with security best practices, including options for secret key, cookie security, and session lifespan. ```APIDOC ## Configuration /api/__mare_serversettings/session.js ### Description Configures Express session middleware, defining settings for session storage, secret, cookie properties, and security. ### Method N/A (Configuration file) ### Endpoint N/A (Configuration file: `/api/__mare_serversettings/session.js`) ### Parameters None ### Request Example N/A ### Response N/A ### Usage Notes - **Environment Variables:** Requires `SESSION_SECRET`. `NODE_ENV` affects `secure` and `sameSite` cookie attributes. - **Security:** `httpOnly: true` and `secure: true` (in production) are recommended for enhanced security. - **`maxAge`:** Configured for 2 hours in the example. ``` -------------------------------- ### API Endpoint - Error Handling Source: https://github.com/emadklenka/marejs/blob/main/README.md Illustrates robust error handling within an API endpoint, catching exceptions and returning appropriate error responses. ```APIDOC ## POST /api/risky-operation ### Description Executes a potentially risky operation and handles any errors gracefully. ### Method POST ### Endpoint `/api/risky-operation` ### Parameters #### Request Body (Assumed to contain necessary data for `riskyOperation` function) ### Request Example ```json { "input": "data" } ``` ### Response #### Success Response (200) - **(response body)** - The data returned by the `riskyOperation` function upon success. #### Error Response (500) - **error** (string) - A message describing the error that occurred. #### Response Example (Success) ```json { "result": "operation successful" } ``` #### Response Example (Error) ```json { "error": "Failed to perform operation: Internal server error message" } ``` ### Notes Logs errors to the console and returns a 500 status code with an error message if `riskyOperation` throws an exception. ``` -------------------------------- ### Basic React Page Component for MareJS Source: https://github.com/emadklenka/marejs/blob/main/README.md A simple React component that serves as a basic page in MareJS. When placed in the `pages` directory (e.g., `pages/about.jsx`), it becomes accessible as a route (e.g., `/about`). ```jsx // pages/about.jsx export default function About() { return

About Us

; } ``` -------------------------------- ### Creating Public API Endpoints Source: https://context7.com/emadklenka/marejs/llms.txt Demonstrates how to create a simple public API endpoint that is accessible without authentication. This uses a standard ES module export. ```APIDOC ## POST /api/public/hello ### Description Creates a simple public API endpoint accessible without authentication. ### Method POST ### Endpoint `/api/public/hello` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:4000/api/public/hello ``` ### Response #### Success Response (200) - **message** (string) - A success message from the API. #### Response Example ```json { "message": "Hello from ES module!..." } ``` ``` -------------------------------- ### MareJS Production Environment Variables (Bash) Source: https://context7.com/emadklenka/marejs/llms.txt Configuration settings for running MareJS in a production environment, defined in a `.env` file. Includes settings for Node.js environment, port, session secrets, security options, and WAF mode. ```bash # .env NODE_ENV=production PORT=4000 SESSION_SECRET=your-secure-random-secret SECURE_COOKIES=true WAF=true WAF_MODE=block JSON_LIMIT=10mb ``` -------------------------------- ### Create Custom API Middleware in JavaScript Source: https://github.com/emadklenka/marejs/blob/main/README.md Defines a custom middleware function for MareJS API endpoints. This function accepts request, response, and next arguments, allowing for logic execution before the main API handler. It's registered in `mare_server.js` using `app.use()`. ```javascript // api/__mare_serversettings/custom-middleware.js export default function customMiddleware(req, res, next) { // Your middleware logic next(); } ``` ```javascript import customMiddleware from './api/__mare_serversettings/custom-middleware.js'; app.use(customMiddleware); ``` -------------------------------- ### MareJS API Endpoint with Error Handling Source: https://github.com/emadklenka/marejs/blob/main/README.md Demonstrates error handling within a MareJS API endpoint. It uses a try-catch block to execute a potentially risky operation and gracefully handles any errors by logging them and sending a 500 Internal Server Error response with the error message. ```javascript export default async function handler(req, res) { try { const data = await riskyOperation(); res.json(data); } catch (error) { console.error('API Error:', error); res.status(500).json({ error: error.message }); } } ``` -------------------------------- ### Dynamic Route Page Component in MareJS Source: https://github.com/emadklenka/marejs/blob/main/README.md A React component for creating dynamic routes in MareJS. The filename uses square brackets (e.g., `pages/user/[id].jsx`) to define a route parameter. The parameter is passed as a prop to the component, allowing for personalized content based on the URL. ```jsx // pages/user/[id].jsx export default function UserPage({ id }) { return

User Profile: {id}

; } ``` -------------------------------- ### Configure WAF Safe Routes (JavaScript & Bash) Source: https://context7.com/emadklenka/marejs/llms.txt Configures routes that bypass Web Application Firewall (WAF) checks. Supports exact path matching, wildcard pattern matching, and partial bypasses for specific methods or checks like XSS and SQLi. Environment variables control WAF behavior. ```javascript // saferoutes.config.js export default { // Complete WAF bypass for exact paths exact: [ "/api/public/webhooks/github", "/api/public/webhooks/stripe" ], // Pattern matching with wildcards patterns: [ "/api/public/webhooks/*", "/api/internal/admin/*" ], // Partial bypasses - disable specific checks partial: [ { path: "/api/blog/post", methods: ["POST", "PUT"], skip: ["xss"], // Allow HTML in blog posts reason: "Blog posts contain legitimate HTML content" }, { path: "/api/code/snippet", skip: ["xss", "sqli"], reason: "Code examples contain SQL and JavaScript syntax" } ] }; ``` ```bash # .env WAF=true # Enable/disable WAF (default: true) WAF_MODE=block # block | log | off WAF_SAFE_ROUTES=true # Enable safe routes config WAF_STRICT=false # Ignore safe routes config ``` -------------------------------- ### Manage Session Configuration in JavaScript Source: https://context7.com/emadklenka/marejs/llms.txt Sets up Express session management with security best practices. It configures session secrets, resave/saveUninitialized options, and secure cookie settings based on the environment (production vs. development). Environment variables are used for sensitive configurations. ```javascript // api/__mare_serversettings/session.js import session from "express-session"; export function getMareSession() { return session({ secret: process.env.SESSION_SECRET || 'your-secret-key-here', resave: false, saveUninitialized: false, cookie: { secure: process.env.NODE_ENV === 'production', httpOnly: true, sameSite: process.env.NODE_ENV === 'production' ? 'strict' : 'lax', maxAge: 1000 * 60 * 60 * 2 // 2 hours } }); } ``` -------------------------------- ### Configure CORS Settings in JavaScript Source: https://context7.com/emadklenka/marejs/llms.txt Configures Cross-Origin Resource Sharing (CORS) settings for the API using the `cors` middleware. It provides different configurations for production (restricted origins) and development (allow all origins). This helps manage cross-domain requests securely. ```javascript // api/__mare_serversettings/cors.js import cors from 'cors'; export function getMarecors() { // Production: Restrict to specific origins return cors({ origin: ['https://yourdomain.com', 'https://app.yourdomain.com'], credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE'], allowedHeaders: ['Content-Type', 'Authorization'] }); // Development: Allow all origins // return cors({ origin: true, credentials: true }); } ``` -------------------------------- ### Create Custom Authentication Middleware (JavaScript) Source: https://context7.com/emadklenka/marejs/llms.txt Implements custom middleware for authentication and authorization checks in a Node.js environment. It decodes request paths to prevent traversal, allows public routes, and verifies JWT tokens. Dependencies include JWT verification logic. ```javascript // api/__mare_serversettings/middleware.js export function mareMiddleware(req, res, next) { // Decode and check for path traversal const decodedPath = decodeURIComponent(req.path); if (decodedPath.includes('..')) { return res.status(400).json({ error: "Invalid path" }); } // Allow public routes if (req.path.startsWith('/public')) { return next(); } // Check authentication token const token = req.headers.authorization?.replace('Bearer ', ''); if (!token) { return res.status(401).json({ error: "Unauthorized: No token provided" }); } try { // Verify JWT token const decoded = verifyToken(token); req.user = decoded; return next(); } catch (error) { return res.status(401).json({ error: "Unauthorized: Invalid token" }); } } function verifyToken(token) { // Your JWT verification logic return { id: '123', email: 'user@example.com' }; } ``` -------------------------------- ### Client-Side WebSocket Chat in React (JSX) Source: https://github.com/emadklenka/marejs/blob/main/README.md This snippet shows how to connect to a WebSocket server from a React component. It manages WebSocket connection state, handles incoming messages by parsing JSON, and allows sending messages with user input. It utilizes `useState` and `useEffect` hooks for state management and side effects, ensuring the WebSocket connection is closed on component unmount. ```jsx import { useState, useEffect } from 'react'; export default function Chat() { const [ws, setWs] = useState(null); const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); useEffect(() => { const websocket = new WebSocket('ws://localhost:4000/api/wss/chat'); websocket.onmessage = (event) => { const data = JSON.parse(event.data); setMessages(prev => [...prev, data]); }; setWs(websocket); return () => websocket.close(); }, []); const sendMessage = () => { if (ws && input.trim()) { ws.send(JSON.stringify({ user: 'User', text: input })); setInput(''); } }; return (
{messages.map((msg, i) => (
{msg.user}: {msg.text}
))}
setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && sendMessage()} />
); } ``` -------------------------------- ### Create WebSocket Chat Handler (Node.js) Source: https://context7.com/emadklenka/marejs/llms.txt This Node.js code defines a WebSocket handler for a chat application. It manages connected clients, broadcasts messages, handles user disconnections, and logs errors. It uses a Set to keep track of active connections and ensures messages are JSON-stringified before sending. ```javascript // api/wss/chat.js const clients = new Set(); export default function chatHandler(ws, req) { console.log('🔌 Chat client connected'); clients.add(ws); // Send welcome message ws.send(JSON.stringify({ type: 'welcome', message: 'Connected to chat!', onlineUsers: clients.size })); // Broadcast user count to all clients broadcast({ type: 'userCount', count: clients.size }); // Handle incoming messages ws.on('message', (data) => { try { const message = JSON.parse(data.toString()); // Broadcast to all clients except sender broadcast({ type: 'message', user: message.user, text: message.text, timestamp: new Date().toISOString() }, ws); } catch (error) { ws.send(JSON.stringify({ type: 'error', message: 'Invalid message format' })); } }); // Handle disconnection ws.on('close', () => { clients.delete(ws); broadcast({ type: 'userCount', count: clients.size }); console.log('🔌 Chat client disconnected'); }); // Handle errors ws.on('error', (error) => { console.error('❌ WebSocket error:', error); clients.delete(ws); }); } function broadcast(message, exclude = null) { const data = JSON.stringify(message); clients.forEach(client => { if (client !== exclude && client.readyState === 1) { client.send(data); } }); } ```