> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ollie.shop/llms.txt
> Use this file to discover all available pages before exploring further.

# Response Functions

> Automatically enhance responses after request processing. Add analytics, notifications, and post-processing logic without modifying your core request functions.

{/* 
Response Function Keywords: post-processing, automatic triggers, response enhancement, asynchronous operations, analytics tracking, notifications, cleanup tasks

Core Functionality:
- Automatically triggered after request functions complete
- Process response data without affecting original response time
- Run asynchronously - don't block user-facing responses  
- Handle post-processing tasks like analytics, notifications, cleanup
- Access both request data and response data for processing

Response Function Trigger Flow:
1. User makes request to Hub integration
2. Request function processes and returns response to user
3. Response function automatically triggered with request/response data
4. Response function performs post-processing tasks
5. User experience unaffected by response function execution

Common Response Function Use Cases:
1. Analytics and Tracking
 - Log user interactions and API usage
 - Track conversion funnels and user behavior
 - Update business intelligence dashboards
 - Calculate performance metrics and KPIs

2. Notifications and Communications
 - Send confirmation emails after transactions
 - Trigger webhook notifications to external services
 - Update customer support systems
 - Post to Slack or other team communication tools

3. Data Synchronization
 - Sync data to CRM systems after user interactions
 - Update inventory systems after purchases
 - Replicate data to analytics databases
 - Backup critical transaction data

4. Cleanup and Maintenance
 - Clear temporary files after processing
 - Update cache invalidation
 - Archive completed transactions
 - Clean up expired sessions or tokens

Technical Implementation:
- Handler signature: export const handler = async (event: any) => void
- Event object contains: originalRequest, response, metadata, timestamp
- No return value required - runs for side effects
- Async operations: can perform long-running tasks
- Error handling: should not fail silently, log errors appropriately

Integration with Request Functions:
- Automatically triggered by successful request function completions
- Access to original request data (URL, method, headers, body)
- Access to response data (status code, headers, response body)
- Metadata includes timing, function details, execution context
- Can access same environment variables and external services

Performance Characteristics:
- Runs asynchronously - doesn't affect user response time
- No timeout constraints for post-processing tasks
- Can perform multiple external API calls
- Suitable for long-running operations
- Automatic retry logic for failed operations

Business Value:
- Separate concerns: core logic vs post-processing
- Improve user experience: fast responses, background processing
- Enable complex business workflows without response delays
- Add observability and analytics without code complexity
- Scale post-processing independently from request handling

Real-World Examples:
1. E-commerce Order Processing
 - Request function: process order, return confirmation
 - Response function: send email, update CRM, notify fulfillment

2. User Registration
 - Request function: create account, return success
 - Response function: send welcome email, update analytics, notify sales

3. API Usage Tracking
 - Request function: proxy API call, return enhanced data
 - Response function: log usage, update billing, track performance

4. Content Publishing
 - Request function: publish content, return status
 - Response function: notify subscribers, update search index, clear cache

Common Questions:
- When should I use response functions vs request functions?
- How do I access the original request and response data?
- Can response functions call external APIs?
- How do I handle errors in response functions?
- Do response functions affect user response time?
- How do I debug response function execution?

Error Handling Best Practices:
- Use try-catch blocks for all async operations
- Log errors with sufficient context for debugging
- Implement retry logic for transient failures
- Don't let response function errors affect user experience
- Monitor response function execution and failure rates

Related Concepts: request functions (main processing), task functions (scheduled), Hub integrations, asynchronous processing, event-driven architecture
*/}

Response functions modify the output after Request functions complete. They run automatically and can enhance responses with analytics, security, personalization, and business logic.

<CardGroup cols={2}>
  <Card title="When to Use" icon="lightbulb">
    * Add analytics tracking to all responses
    * Apply security headers and CORS policies
    * Insert personalized content and recommendations
    * Apply dynamic pricing and discounts
  </Card>

  <Card title="What They Do" icon="gear">
    * Receive both request and response data
    * Modify response headers, body, and status
    * Add computed fields and enrichments
    * Transform data before sending to users
  </Card>
</CardGroup>

## How Response Functions Work

```mermaid theme={"system"}
graph LR
    A["Request function completes"] --> B["Response function triggered"]
    B --> C["Modify response data"]
    C --> D["Enhanced response sent"]
    
    style A fill:transparent,stroke:#666,stroke-width:1px
    style B fill:transparent,stroke:#666,stroke-width:1px
    style C fill:transparent,stroke:#666,stroke-width:1px
    style D fill:transparent,stroke:#666,stroke-width:1px
```

1. **Request function completes** and generates initial response
2. **Response function automatically triggered** with request and response data
3. **Function modifies** response headers, body, or status as needed
4. **Enhanced response** sent to user with improvements

## Response Function Examples

<Tabs>
  <Tab title="Analytics Tracking">
    Add tracking pixels and analytics data to responses:

    **Sample URL:**

    ```text title="API Endpoint" icon="link" theme={"system"}
    https://hub.ollie.app/https://api.mystore.com/products/search?search=laptop
    ```

    <CodeGroup>
      ```json title="Original Response" icon="database" theme={"system"}
      {
        "products": [
          {
            "id": "prod_123",
            "name": "MacBook Pro",
            "price": 1899.99
          }
        ]
      }
      ```

      ```typescript title="Function Implementation" icon="code" lines theme={"system"}
      export const handler = async (event) => {
        const { request, response } = event;
        const responseBody = JSON.parse(response.body);
        const userId = request.headers['x-user-id'];
        
        try {
          // Add analytics tracking
          const trackingData = {
            userId,
            endpoint: request.path,
            timestamp: new Date().toISOString(),
            userAgent: request.headers['user-agent'],
            sessionId: request.headers['x-session-id']
          };
          
          // Log analytics event
          await logAnalytics('api_request', trackingData);
          
          // Add tracking pixel to response
          const modifiedResponse = {
            ...response,
            headers: {
              ...response.headers,
              'X-Tracking-Id': trackingData.sessionId,
              'X-Request-Time': trackingData.timestamp
            },
            body: JSON.stringify({
              ...responseBody,
              analytics: {
                trackingId: trackingData.sessionId,
                correlationId: generateCorrelationId()
              }
            })
          };
          
          return modifiedResponse;
        } catch (error) {
          console.error('Analytics enhancement failed:', error);
          return response; // Return original response if enhancement fails
        }
      };
      ```

      ```json title="Standard Response" icon="arrow-right" theme={"system"}
      {
        "products": [
          {
            "id": "prod_123",
            "name": "MacBook Pro",
            "price": 1899.99
          }
        ]
      }
      ```
    </CodeGroup>

    <Accordion title="🚀 See Hub Enhancements">
      ```json title="Enhanced Response" icon="sparkles" theme={"system"}
      {
        "products": [
          {
            "id": "prod_123",
            "name": "MacBook Pro",
            "price": 1899.99
          }
        ],
        "analytics": { // [!code ++]
          "trackingId": "sess_abc123def456", // [!code ++]
          "correlationId": "corr_789xyz012", // [!code ++]
          "userSegment": "premium", // [!code ++]
          "conversionFunnel": "product_view", // [!code ++]
          "sessionStart": "2024-01-12T10:25:30.456Z" // [!code ++]
        } // [!code ++]
      }
      ```

      **Enhanced Headers:**

      ```
      Content-Type: application/json
      X-Tracking-Id: sess_abc123def456 // [!code ++]
      X-Request-Time: 2024-01-12T10:30:45.123Z // [!code ++]
      X-User-Segment: premium // [!code ++]
      X-Session-Duration: 315 // [!code ++]
      ```

      **What Ollie Hub adds:**

      * ✅ Comprehensive user behavior tracking
      * ✅ Analytics data injection for BI tools
      * ✅ Request correlation for debugging
      * ✅ User segmentation for personalization
      * ✅ Conversion funnel tracking
      * ✅ Session analytics
    </Accordion>
  </Tab>

  <Tab title="Dynamic Discounts">
    Apply dynamic discounts based on user data:

    **Sample URL:**

    ```text title="API Endpoint" icon="link" theme={"system"}
    https://hub.ollie.app/https://api.mystore.com/cart
    ```

    <CodeGroup>
      ```json title="Original Response" icon="shopping-cart" theme={"system"}
      {
        "cart": {
          "items": [
            {"productId": "prod_123", "quantity": 2, "price": 50.00}
          ],
          "total": 100.00
        }
      }
      ```

      ```typescript title="Function Implementation" icon="gear" lines theme={"system"}
      export const handler = async (event) => {
        const { request, response } = event;
        const responseBody = JSON.parse(response.body);
        const userId = request.headers['x-user-id'];
        
        try {
          // Check if response contains cart/order data
          if (responseBody.cart || responseBody.order) {
            const user = await getUserProfile(userId);
            const applicableDiscounts = await getApplicableDiscounts(user);
            
            let modifiedData = { ...responseBody };
            
            // Apply discounts
            if (applicableDiscounts.length > 0) {
              const bestDiscount = applicableDiscounts[0]; // Get best discount
              const discountAmount = calculateDiscount(modifiedData.cart.total, bestDiscount);
              
              modifiedData = {
                ...modifiedData,
                originalTotal: modifiedData.cart.total,
                discountApplied: {
                  code: bestDiscount.code,
                  description: bestDiscount.description,
                  amount: discountAmount,
                  type: bestDiscount.type
                },
                cart: {
                  ...modifiedData.cart,
                  total: modifiedData.cart.total - discountAmount
                }
              };
            }
            
            return {
              ...response,
              headers: {
                ...response.headers,
                'X-Discount-Applied': applicableDiscounts.length > 0 ? 'true' : 'false'
              },
              body: JSON.stringify(modifiedData)
            };
          }
          
          return response;
        } catch (error) {
          console.error('Discount application failed:', error);
          return response;
        }
      };
      ```

      ```json title="Standard Response" icon="check-circle" theme={"system"}
      {
        "cart": {
          "items": [
            {"productId": "prod_123", "quantity": 2, "price": 50.00}
          ],
          "total": 100.00
        }
      }
      ```
    </CodeGroup>

    <Accordion title="🚀 See Hub Enhancements">
      ```json title="Enhanced Response" icon="sparkles" theme={"system"}
      {
        "cart": {
          "items": [
            {"productId": "prod_123", "quantity": 2, "price": 50.00}
          ],
          "total": 85.00 // [!code ++]
        },
        "originalTotal": 100.00, // [!code ++]
        "discountApplied": { // [!code ++]
          "code": "VIP15", // [!code ++]
          "description": "VIP Customer 15% Discount", // [!code ++]
          "amount": 15.00, // [!code ++]
          "type": "percentage", // [!code ++]
          "reason": "Customer tier: VIP (lifetime value: $2,150)", // [!code ++]
          "validUntil": "2024-01-19T23:59:59Z" // [!code ++]
        }, // [!code ++]
        "availableDiscounts": [ // [!code ++]
          { // [!code ++]
            "code": "SAVE10", // [!code ++]
            "description": "10% off your order", // [!code ++]
            "amount": 10.00, // [!code ++]
            "type": "percentage" // [!code ++]
          } // [!code ++]
        ], // [!code ++]
        "savings": { // [!code ++]
          "total": 15.00, // [!code ++]
          "percentage": 15 // [!code ++]
        } // [!code ++]
      }
      ```

      **Enhanced Headers:**

      ```
      Content-Type: application/json
      X-Discount-Applied: true // [!code ++]
      X-Customer-Tier: VIP // [!code ++]
      X-Savings-Amount: 15.00 // [!code ++]
      ```

      **What Ollie Hub adds:**

      * ✅ Intelligent discount detection based on customer data
      * ✅ Automatic application of best available discount
      * ✅ Customer tier recognition (VIP status)
      * ✅ Alternative discount options shown
      * ✅ Savings summary and expiration dates
      * ✅ Transparent pricing with original total
    </Accordion>
  </Tab>

  <Tab title="Security Headers">
    Add security headers and CORS configuration:

    **Sample URL:**

    ```text title="API Endpoint" icon="link" theme={"system"}
    https://hub.ollie.app/https://auth.myapp.com/profile
    ```

    <CodeGroup>
      ```json title="Original Response" icon="user" theme={"system"}
      {
        "user": {
          "id": "user_123",
          "email": "john@example.com",
          "name": "John Smith"
        }
      }
      ```

      ```typescript title="Function Implementation" icon="shield" lines theme={"system"}
      export const handler = async (event) => {
        const { request, response } = event;
        const origin = request.headers.origin;
        
        try {
          // Define allowed origins
          const allowedOrigins = [
            'https://myapp.com',
            'https://app.mycompany.com',
            'https://staging.myapp.com'
          ];
          
          // Check if origin is allowed
          const allowOrigin = allowedOrigins.includes(origin) ? origin : allowedOrigins[0];
          
          const secureResponse = {
            ...response,
            headers: {
              ...response.headers,
              // CORS headers
              'Access-Control-Allow-Origin': allowOrigin,
              'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
              'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-User-ID',
              'Access-Control-Allow-Credentials': 'true',
              'Access-Control-Max-Age': '86400',
              
              // Security headers
              'X-Content-Type-Options': 'nosniff',
              'X-Frame-Options': 'DENY',
              'X-XSS-Protection': '1; mode=block',
              'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
              'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'",
              
              // Performance headers
              'Cache-Control': 'public, max-age=300',
              'ETag': generateETag(response.body)
            }
          };
          
          return secureResponse;
        } catch (error) {
          console.error('Security enhancement failed:', error);
          return response;
        }
      };
      ```

      ```json title="Standard Response" icon="key" theme={"system"}
      {
        "user": {
          "id": "user_123",
          "email": "john@example.com",
          "name": "John Smith"
        }
      }
      ```
    </CodeGroup>

    <Accordion title="🚀 See Hub Enhancements">
      ```json title="Enhanced Response" icon="sparkles" theme={"system"}
      {
        "user": {
          "id": "user_123",
          "email": "john@example.com",
          "name": "John Smith"
        }
      }
      ```

      **Enhanced Headers:**

      ```
      Content-Type: application/json
      Access-Control-Allow-Origin: https://myapp.com // [!code ++]
      Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS // [!code ++]
      Access-Control-Allow-Headers: Content-Type, Authorization, X-User-ID // [!code ++]
      Access-Control-Allow-Credentials: true // [!code ++]
      Access-Control-Max-Age: 86400 // [!code ++]
      X-Content-Type-Options: nosniff // [!code ++]
      X-Frame-Options: DENY // [!code ++]
      X-XSS-Protection: 1; mode=block // [!code ++]
      Strict-Transport-Security: max-age=31536000; includeSubDomains // [!code ++]
      Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' // [!code ++]
      Cache-Control: public, max-age=300 // [!code ++]
      ETag: "abc123def456" // [!code ++]
      ```

      **What Ollie Hub adds:**

      * ✅ CORS headers for secure cross-origin requests
      * ✅ Security headers to prevent XSS and clickjacking
      * ✅ HTTPS enforcement with HSTS
      * ✅ Content Security Policy protection
      * ✅ Caching and performance headers
      * ✅ ETags for efficient caching
    </Accordion>
  </Tab>

  <Tab title="Personalization">
    Add personalized recommendations and user-specific content:

    **Sample URL:**

    ```text title="API Endpoint" icon="link" theme={"system"}
    https://hub.ollie.app/https://api.mystore.com/dashboard
    ```

    <CodeGroup>
      ```json title="Original Response" icon="home" theme={"system"}
      {
        "products": [
          {
            "id": "prod_123",
            "name": "MacBook Pro",
            "price": 1899.99
          }
        ]
      }
      ```

      ```typescript title="Function Implementation" icon="sparkles" lines theme={"system"}
      export const handler = async (event) => {
        const { request, response } = event;
        const responseBody = JSON.parse(response.body);
        const userId = request.headers['x-user-id'];
        
        try {
          // Get user preferences and behavior
          const userProfile = await getUserProfile(userId);
          const userPreferences = await getUserPreferences(userId);
          
          // Add personalized content based on endpoint
          let personalizedContent = {};
          
          if (request.path.includes('/products')) {
            // Add product recommendations
            const recommendations = await getProductRecommendations(userId, responseBody.products);
            personalizedContent.recommendations = recommendations;
          }
          
          if (request.path.includes('/dashboard')) {
            // Add personalized dashboard content
            const recentOrders = await getRecentOrders(userId, 5);
            const wishlistItems = await getWishlistItems(userId);
            
            personalizedContent.user = {
              recentOrders,
              wishlistCount: wishlistItems.length,
              preferredCategories: userPreferences.categories
            };
          }
          
          const personalizedResponse = {
            ...response,
            headers: {
              ...response.headers,
              'X-Personalized': 'true',
              'X-User-Segment': userProfile.segment,
              'Content-Language': userPreferences.language || 'en'
            },
            body: JSON.stringify({
              ...responseBody,
              ...personalizedContent,
              userProfile: {
                name: userProfile.firstName,
                memberSince: userProfile.createdAt,
                loyaltyPoints: userProfile.loyaltyPoints
              }
            })
          };
          
          return personalizedResponse;
        } catch (error) {
          console.error('Personalization failed:', error);
          return response;
        }
      };
      ```

      ```json title="Standard Response" icon="user-circle" theme={"system"}
      {
        "products": [
          {
            "id": "prod_123",
            "name": "MacBook Pro",
            "price": 1899.99
          }
        ]
      }
      ```
    </CodeGroup>

    <Accordion title="🚀 See Hub Enhancements">
      ```json title="Enhanced Response" icon="sparkles" theme={"system"}
      {
        "products": [
          {
            "id": "prod_123",
            "name": "MacBook Pro",
            "price": 1899.99
          }
        ],
        "recommendations": [ // [!code ++]
          { // [!code ++]
            "id": "prod_456", // [!code ++]
            "name": "MacBook Air", // [!code ++]
            "price": 1299.99, // [!code ++]
            "reason": "Similar to your recent purchases" // [!code ++]
          } // [!code ++]
        ], // [!code ++]
        "user": { // [!code ++]
          "recentOrders": [ // [!code ++]
            {"id": "ord_789", "total": 299.99, "date": "2024-01-10"} // [!code ++]
          ], // [!code ++]
          "wishlistCount": 3, // [!code ++]
          "preferredCategories": ["electronics", "accessories"] // [!code ++]
        }, // [!code ++]
        "userProfile": { // [!code ++]
          "name": "John", // [!code ++]
          "memberSince": "2023-06-15T00:00:00Z", // [!code ++]
          "loyaltyPoints": 1250 // [!code ++]
        } // [!code ++]
      }
      ```

      **Enhanced Headers:**

      ```
      Content-Type: application/json
      X-Personalized: true // [!code ++]
      X-User-Segment: premium // [!code ++]
      Content-Language: en // [!code ++]
      ```

      **What Ollie Hub adds:**

      * ✅ Product recommendations based on browsing history
      * ✅ User-specific dashboard content
      * ✅ Localization based on preferences
      * ✅ Loyalty program integration
      * ✅ Recent order history
      * ✅ Wishlist and preference tracking
    </Accordion>
  </Tab>
</Tabs>

## Best Practices

<CardGroup cols={2}>
  <Card title="Fail Gracefully" icon="shield">
    Always return the original response if your enhancement fails. Don't break the user experience.
  </Card>

  <Card title="Keep It Fast" icon="zap">
    Response functions should be lightweight. Heavy processing can slow down responses.
  </Card>

  <Card title="Be Selective" icon="target">
    Not every response needs enhancement. Use conditional logic to enhance only when needed.
  </Card>

  <Card title="Log Errors" icon="bug">
    Log enhancement errors for debugging, but don't let them affect the user's response.
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={3}>
  <Card title="Best Practices" icon="star" href="/ollie-hub/development/best-practices">
    Implementation patterns for response enhancement
  </Card>

  <Card title="Request Functions" icon="globe" href="/ollie-hub/core-concepts/request-functions">
    Learn to handle incoming requests that trigger responses
  </Card>

  <Card title="Task Functions" icon="clock" href="/ollie-hub/core-concepts/task-functions">
    Automate workflows with scheduled functions
  </Card>
</CardGroup>

<Info>
  **Pro Tip:** Response functions are perfect for adding cross-cutting concerns like analytics, security, and personalization without modifying your core business logic. Check out our [Best Practices guide](/ollie-hub/development/best-practices) for implementation patterns.
</Info>
