Connect and automate

Pre Hooks (Detailed Guide)

Comprehensive guide on building server-side middleware to run logic before data is saved.

Backend engineers12 min read

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:

  1. Authentication: The API Gateway verifies the API Key or JWT.
  2. Hook Execution: If a Before Insert Pre Hook exists on the orders table, execution jumps to your defined sequential steps.
  3. Database Commit: If the hook completes successfully, the manipulated payload is written to the database.
  4. Response: The client receives a 201 Created status 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

  1. Navigate to the Pre Hooks section in your dashboard.
  2. Click Create Pre Hook.
  3. Table: Select orders.
  4. Trigger Event: Select Before Insert (POST).
  5. Click Save & Edit Steps.

Step 2.2: Validating Incoming Data

We must ensure the user isn't trying to order 0 or negative items.

  1. Click + Add Step.
  2. Select Condition (If/Else).
  3. Set the condition: payload.quantity is less than or equal to 0.
  4. Inside the THEN block, click + Add Action.
  5. Select Throw Error.
  6. 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.

  1. Click + Add Step (outside the previous IF block).
  2. Select Transform / Set Field.
  3. Target Field: payload.total_amount
  4. Operation: Select Calculate (Math).
  5. Formula: payload.price * payload.quantity

Step 2.4: Setting Defaults

  1. Click + Add Step.
  2. Select Transform / Set Field.
  3. Target Field: payload.status
  4. 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 / OR conditions within a single block.
  • You can nest steps inside the THEN and ELSE pathways.

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, the payload object only contains the fields the client sent in the request. If the client sends a PATCH updating only the status, payload.price will be undefined. You must use the If/Else step 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 Delete hook, you can check if 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 send quantity in the JSON body.
  • Resolution: Wrap the math step in an If condition that checks if payload.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.
Pre Hooks (Detailed Guide) | Help Center