Pre Hooks (Detailed Guide)
Comprehensive guide on building server-side middleware to run logic before data is saved.
Pre Hooks: Server-Side Middleware for NoCodeBackend
Pre Hooks are the most powerful feature in NoCodeBackend. They allow you to execute custom business logic exactly before data is inserted, updated, or deleted in your MySQL database.
Because NoCodeBackend automatically generates your REST API endpoints, you do not have a traditional "backend controller" where you would normally write validation or transformation logic. Pre Hooks bridge this gap by letting you intercept incoming API requests, manipulate the payload, and enforce strict server-side rules before the transaction commits.
1. Detailed Overview
A Pre Hook is essentially synchronous middleware attached to a specific table and HTTP method.
When a client makes an API request (e.g., POST /orders), the flow is as follows:
- Authentication: The API Gateway verifies the API Key or JWT.
- Hook Execution: If a
Before InsertPre Hook exists on theorderstable, execution jumps to your defined sequential steps. - Database Commit: If the hook completes successfully, the manipulated payload is written to the database.
- Response: The client receives a
201 Createdstatus with the final data.
Why use Pre Hooks instead of Frontend Logic?
Never trust the client. If you rely on your React frontend to calculate the total price of an order (price * quantity), a malicious user can intercept the network request and change the total to $0.00 before it hits the database.
By using a Pre Hook to enforce payload.total = payload.price * payload.quantity, the calculation happens securely on the server, making it impossible for a bad actor to manipulate the final price.
2. Step-by-Step Guide: Building a Secure Checkout Hook
Let's build a hook for an orders table that calculates the total price, ensures the user isn't ordering negative quantities, and defaults the status to 'pending'.
Step 2.1: Creating the Hook
- Navigate to the Pre Hooks section in your dashboard.
- Click Create Pre Hook.
- Table: Select
orders. - Trigger Event: Select
Before Insert (POST). - Click Save & Edit Steps.
Step 2.2: Validating Incoming Data
We must ensure the user isn't trying to order 0 or negative items.
- Click + Add Step.
- Select Condition (If/Else).
- Set the condition:
payload.quantityis less than or equal to0. - Inside the
THENblock, click + Add Action. - Select Throw Error.
- Set HTTP Status Code to
400. Set Error Message to"Quantity must be greater than zero."
Step 2.3: Calculating the Total
Next, we ignore whatever total the client sent and forcefully calculate it ourselves.
- Click + Add Step (outside the previous IF block).
- Select Transform / Set Field.
- Target Field:
payload.total_amount - Operation: Select
Calculate (Math). - Formula:
payload.price * payload.quantity
Step 2.4: Setting Defaults
- Click + Add Step.
- Select Transform / Set Field.
- Target Field:
payload.status - Operation:
Set Static Value->'pending'
Now, whenever a POST request hits /orders, it will be validated, securely calculated, and formatted before touching the database.
3. Configuration & Parameters
Every step in a Pre Hook interacts with the payload object, which represents the incoming JSON body of the HTTP request.
Available Step Types
1. Validate Field
A shorthand for If/Else -> Throw Error. It asserts a condition must be true.
- Properties: Target Field, Operator (Equals, Contains, > , <, Regex), Value.
2. Transform / Set Field
Modifies the payload.
- Set Static: Hardcode a string, boolean, or number.
- Calculate: Perform basic arithmetic (
+,-,*,/) between fields. - Format: Lowercase, Uppercase, Trim whitespace.
3. Condition (If/Else)
Creates logical branching.
- You can stack multiple
AND/ORconditions within a single block. - You can nest steps inside the
THENandELSEpathways.
4. Fetch Record (Coming Soon)
Query another table during the hook to validate relationships (e.g., Fetching the products table to ensure products.stock_count > payload.quantity).
4. Best Practices & Edge Cases
- Synchronous Execution: Pre Hooks run synchronously. This means the client making the API call is waiting for the hook to finish. Keep your logic lean. Do not put heavy operations inside a Pre Hook. If you need to send an email, use an Outbound Webhook instead, which runs asynchronously after the database commits.
- The Payload object in Updates: During a
Before Update (PUT/PATCH)hook, thepayloadobject only contains the fields the client sent in the request. If the client sends aPATCHupdating only thestatus,payload.pricewill beundefined. You must use theIf/Elsestep to check if a field exists before performing math on it during updates. - Security Validation: Use Pre Hooks extensively for Row Level Security enforcement. For example, during a
Before Deletehook, you can checkif payload.user_id != context.user.id -> Throw 403 Forbidden.
5. Troubleshooting
Common Errors
Error: Hook execution failed: Cannot read property 'quantity' of undefined
- Cause: You attempted a Math calculation (
payload.price * payload.quantity) on an update request, but the client didn't sendquantityin the JSON body. - Resolution: Wrap the math step in an
Ifcondition that checks ifpayload.quantity is not empty.
Error: API Request timeout
- Cause: You have configured too many nested conditions or complex regex validations, causing the execution to bottleneck.
- Resolution: Simplify your logic. Pre Hooks are meant for quick validation and transformation, not deep data processing.
Error: Client receives 400 Bad Request unexpectedly
- Cause: One of your Validate Field steps failed, but you didn't provide a custom error message, so the client receives a generic rejection.
- Resolution: Always provide clear, descriptive error messages in your validation and Throw Error steps so frontend developers know exactly what data was rejected.
