> ## Documentation Index
> Fetch the complete documentation index at: https://base-a060aa97-danc-alpha-docs.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Understanding Mini App Context

> Leverage context data to build social-first mini applications that adapt to user entry points and drive viral growth

Context is the environmental data that is automatically provided to your mini app which describes how, where, and by whom your mini app was launched. This guide shows you how to leverage context to create personalized experiences and optimize viral growth.

## What is Context?

Context provides three essential data objects that shape your user experience:

<CardGroup cols={3}>
  <Card title="User Information" icon="user">
    Profile data of the person using your app
  </Card>

  <Card title="Client Details" icon="mobile">
    Information about the host platform and device
  </Card>

  <Card title="Location Context" icon="map-pin">
    How the user discovered and launched your app
  </Card>
</CardGroup>

<Warning>
  **Context is only available within a Farcaster client such as the Base App, not on the web.**
  If your mini app is accessed via a standard web browser, context data will not be provided. Design your app to gracefully handle the absence of context when running outside the Base App environment.
</Warning>

## Why Context Matters

Context enables you to create mini apps that feel native to their social environment and optimize for viral growth:

| Use Case                | Benefit                                                    |
| ----------------------- | ---------------------------------------------------------- |
| **Personalized UX**     | Customize interface based on user identity and entry point |
| **Viral Optimization**  | Track and optimize discovery paths for growth              |
| **Platform Adaptation** | Adjust functionality for different host platforms          |
| **Social Engagement**   | Leverage social context for community features             |

## Core Context Structure

### User Object

Contains profile information about the person using your mini app:

```typescript User Object Structure
{
  "user": {
    "fid": 20390,
    "username": "sohey", 
    "displayName": "Soheybuildson.base",
    "pfpUrl": "https://imagedelivery.net/BXluQx4ige9GuW0Ia56BHw/..."
  }
}
```

<AccordionGroup>
  <Accordion title="User Object Properties">
    * **fid**: Unique Farcaster identifier for the user
    * **username**: Handle without @ symbol
    * **displayName**: User's chosen display name
    * **pfpUrl**: Profile picture URL
  </Accordion>
</AccordionGroup>

### Client Object

Information about the host platform and device:

```typescript Client Object Structure
{
  "client": {
    "clientFid": 309857,        // Base app identifier
    "added": false,             // App save status
    "platformType": "mobile",   // Device type
    "safeAreaInsets": {
      "top": 0,
      "bottom": 34,
      "left": 0, 
      "right": 0
    }
  }
}
```

<AccordionGroup>
  <Accordion title="Client Object Properties">
    * **clientFid**: Identifies the host app (309857 = Base app)
    * **added**: Whether user has saved your mini app
    * **platformType**: Device type for responsive design
    * **safeAreaInsets**: Safe zones to avoid system UI overlap
  </Accordion>
</AccordionGroup>

### Location Object

Describes how the user discovered your mini app - critical for viral optimization:

<Tabs>
  <Tab title="Launcher Entry">
    ```typescript
    {
      "location": {
        "type": "launcher"
      }
    }
    ```

    <Info>
      **User Journey**: Returning user opening from saved apps\
      **Strategy**: Focus on retention and progression features
    </Info>
  </Tab>

  <Tab title="Messaging Entry">
    ```typescript
    {
      "location": {
        "type": "messaging"
      }
    }
    ```

    <Info>
      **User Journey**: Discovery through private messages\
      **Strategy**: Encourage broader social sharing
    </Info>
  </Tab>

  <Tab title="Cast Embed Entry">
    ```typescript
    {
      "location": {
        "type": "cast_embed",
        "embed": "https://frames-v2-demo-lilac.vercel.app/",
        "cast": {
          "author": {
            "fid": 20390,
            "username": "sohey",
            "displayName": "Soheybuildson.base", 
            "pfpUrl": "https://imagedelivery.net/..."
          },
          "fid": 20390,
          "hash": "0x96178d931158cebbdad1b647b6549f0bb05709ed",
          "timestamp": 1755781905000,
          "text": "Check out this mini app!",
          "embeds": ["https://frames-v2-demo-lilac.vercel.app/"]
        }
      }
    }
    ```

    <Info>
      **User Journey**: Primary viral discovery through social feeds\
      **Strategy**: Optimize first-time experience and immediate engagement
    </Info>
  </Tab>
</Tabs>

## Implementation Guide

<Steps>
  <Step title="Access Context Data">
    Import and use the `useMiniKit()` hook to access context:

    ```typescript
    'use client';
    import { useMiniKit, useIsInMiniApp } from '@coinbase/onchainkit/minikit';
    import { useEffect } from 'react';

    function MyMiniApp() {
      const { context, isFrameReady, setFrameReady } = useMiniKit();

      const { isInMiniApp } = useIsInMiniApp();
      
      useEffect(() => {
        if (!isFrameReady) {
          setFrameReady();
        }
      }, [setFrameReady, isFrameReady]);
      
      // Always check for context availability
      if (isInMiniApp && !context) {
        return <div>Loading...</div>;
      }
      
      // Access context data
      const user = context.user;
      const client = context.client;
      const location = context.location;
      
      return <AppContent />;
    }
    ```

    <Warning>
      Always check for context availability before accessing its properties to avoid runtime errors.
    </Warning>
  </Step>

  <Step title="Create Context-Driven Experiences">
    Design different experiences based on entry point:

    ```typescript
    'use client';
    import { useMiniKit } from '@coinbase/onchainkit/minikit';
    import { useEffect } from 'react';

    function ContextAwareApp() {
      const { context, isFrameReady, setFrameReady } = useMiniKit();
      
      useEffect(() => {
        if (!isFrameReady) {
          setFrameReady();
        }
      }, [setFrameReady, isFrameReady]);
      
      if (!context) return <div>Loading...</div>;
      
      switch (context.location?.type) {
        case 'cast_embed':
          return <ViralOnboarding castAuthor={context.location.cast.author} />;
        case 'launcher': 
          return <ReturningUserDashboard />;
        case 'messaging':
          return <PrivateShareExperience />;
        default:
          return <DefaultExperience />;
      }
    }
    ```

    <Check>
      This approach ensures users get personalized experiences based on how they discovered your app.
    </Check>
  </Step>

  <Step title="Implement Safe Area Support">
    Ensure your UI doesn't overlap with system elements:

    ```typescript
    'use client';
    import { useMiniKit } from '@coinbase/onchainkit/minikit';

    function ResponsiveLayout({ children }) {
      const { context } = useMiniKit();
      const insets = context?.client?.safeAreaInsets;
      
      return (
        <div 
          className="app-container"
          style={{
            paddingTop: insets?.top || 0,
            paddingBottom: insets?.bottom || 0,
            paddingLeft: insets?.left || 0,
            paddingRight: insets?.right || 0,
          }}
        >
          {children}
        </div>
      );
    }
    ```

    <Tip>
      Safe area implementation is crucial for mobile experiences to avoid system UI overlap.
    </Tip>
  </Step>

  <Step title="Add Social Features">
    Leverage cast embed data for social engagement:

    ```typescript
    import { useComposeCast, useViewProfile } from '@coinbase/onchainkit/minikit';

    function SocialAcknowledgment() {
      const { context } = useMiniKit();
      const { composeCast } = useComposeCast();
      const viewProfile = useViewProfile();
      
      if (context?.location?.type !== 'cast_embed') {
        return null;
      }
      
      const { author, text, timestamp,hash } = context.location.cast;
      
      const handleThankSharer = () => {
        composeCast({
          text: `Thanks @${author.username} for sharing this awesome mini app! 🙏`,
          // Optionally include the original cast as parent
          parent: {
            type: 'cast',
            hash: hash
          }
        });
      };
      
      const handleViewProfile = () => {
        viewProfile(author.fid);
      };
      
      return (
        <div className="social-credit">
          <img src={author.pfpUrl} alt={author.displayName} />
          <div>
            <p><strong>@{author.username}</strong> shared this app</p>
            <p>"{text}"</p>
            <div className="action-buttons">
              <button onClick={handleThankSharer}>
                Thank them! 🙏
              </button>
              <button onClick={handleViewProfile}>
                View Profile
              </button>
            </div>
          </div>
        </div>
      );
    }
    ```
  </Step>
</Steps>

## Analytics and Growth Tracking

<Note>
  **Leverage** [Base.dev](https://www.base.dev/) provides comprehensive analytics out-of-the-box including user engagement metrics, entry point analysis, and session tracking. Import your mini app to Base.dev to access real-time analytics that complement your context-driven insights.
</Note>

### Viral Attribution

Track how users discover your app to optimize growth:

```typescript Analytics Implementation
function trackDiscovery() {
  const { context } = useMiniKit();
  
  const discoveryData = {
    type: context?.location?.type,
    platform: context?.client?.platformType,
    userAdded: context?.client?.added,
  };
  
  if (context?.location?.type === 'cast_embed') {
    discoveryData.sharedBy = context.location.cast.author.username;
    discoveryData.castHash = context.location.cast.hash;
  }
  
  analytics.track('mini_app_launch', discoveryData);
}
```

### Growth Metrics to Monitor

| Metric                   | Context Source                   | Optimization Goal           |
| ------------------------ | -------------------------------- | --------------------------- |
| **Cast Embed Launches**  | `location.type === 'cast_embed'` | Maximize viral sharing      |
| **Return User Rate**     | `location.type === 'launcher'`   | Improve retention           |
| **Share Attribution**    | `cast.author` data               | Identify top advocates      |
| **Platform Performance** | `client.platformType`            | Optimize for mobile/desktop |

## Next Steps

<Tip>
  Understanding and leveraging context is foundational to creating mini apps that feel native to their social environment and drive sustainable viral growth.
</Tip>

<CardGroup cols={2}>
  <Card title="Implement Context Access" icon="code">
    Add `useMiniKit()` to your main component and validate context data
  </Card>

  <Card title="Create Entry Point Flows" icon="flow-chart">
    Design different experiences for each location type
  </Card>

  <Card title="Add Safe Area Support" icon="mobile">
    Implement responsive padding for mobile experiences
  </Card>

  <Card title="Track Viral Metrics" icon="chart-line">
    Set up analytics for growth measurement and optimization
  </Card>
</CardGroup>
