# https://docs.base.org/builderkits/minikit/llms.txt
## MiniKit Documentation
This file contains structured documentation for AI assistants about MiniKit, a toolkit for building mini applications that can be featured on Warpcast and Coinbase Wallet with minimal code.
Please refer to https://docs.base.org/llms-full.txt for the complete Base documentation.
---
title: MiniKit Alpha | Getting started
description: Easiest way to build Mini Apps on Base
---
# MiniKit
MiniKit is easiest way to build Mini Apps on Base, allowing developers to easily build applications without needing to know the details of the SDK implementation. It integrates seamlessly with OnchainKit components and provides Coinbase Wallet-specific hooks.
## Why MiniKit?
MiniKit streamlines mini-app development by providing a comprehensive toolkit that makes complex Frames SDK interactions intuitive:
- **Simplified Development:** Build apps with minimal knowledge of the Frames SDK
- **Coinbase Wallet Integration:** Access Coinbase Wallet-specific hooks
- **Component Compatibility:** Use [OnchainKit](https://onchainkit.xyz/) components out of the box with MiniKit
- **Automatic Setup:** CLI tool for quick project scaffolding with webhooks and notifications
- **Account Association:** Simplified generation of account associations
## Use Cases
- Gaming mini apps
- Social mini apps
- Payment mini apps
- And many more possibilities!
## Quick Start
The fastest way to get started with MiniKit is to use the CLI to bootstrap a new project:
```bash
npx create-onchain --mini
```
This command will:
1. Set up a new project with both frontend and backend components
2. Configure webhooks and notifications
3. Set up account association generation
4. Create a demo app showcasing onchain abilities using OnchainKit
After running the command, follow the prompts to configure your project.
:::info
We recommend using [Vercel](https://vercel.com) to deploy your MiniKit app, as it integrates seamlessly with the upstash/redis backend required for frames, webhooks, and notifications. The CLI will guide you through setting up the necessary environment variables for your Redis database.
:::
## Provider
The `MiniKitProvider` wraps your application and provides global access to the SDK's context. It handles initialization, events, and automatically applies client safeAreaInsets to ensure your app doesn't overlap parent application elements.
```tsx
import { MiniKitProvider } from '@coinbase/onchainkit/minikit';
function App({ children }) {
return (
{children}
);
}
```
### Props
The `MiniKitProvider` accepts the following props:
```tsx
export type MiniKitProviderReact = {
children: React.ReactNode;
notificationProxyUrl?: string;
...OnchainKitProviderProps
};
```
- `children`: React components to be wrapped by the provider
- `notificationProxyUrl`: Optional URL to override the default `/api/notification` proxy
- All props from `OnchainKitProvider` are also supported
The provider sets up wagmi and react-query providers automatically. It configures connectors to use the Farcaster connector if `sdk.context` is set, with a fallback to CoinbaseWallet. This allows the same application to run both in frames and as a standalone application.
## Hooks
MiniKit provides several utility hooks that wrap the SDK functionality, making it easy to access different features.
### useMiniKit
This hook handles initialization of the application and provides access to the SDK context.
```tsx
const { setFrameReady, isFrameReady, context, updateClientContext, notificationProxyUrl } = useMiniKit();
// Call setFrameReady() when your app is ready to be shown
useEffect(() => {
if (!isFrameReady) {
setFrameReady();
}
}, [isFrameReady, setFrameReady]);
```
**Returns:**
```tsx
{
ready: () => Promise; // Removes splash screen and shows the application
isReady: boolean; // Whether the app is ready to be shown
context: FrameContext | null; // The current frame context
updateClientContext: (params: UpdateClientContextParams) => void; // Update client context
notificationProxyUrl: string; // The notification proxy URL
}
```
### useAddFrame
This hook adds a frame to the user's list of frames and returns notification details.
```tsx
const addFrame = useAddFrame();
// Usage
const handleAddFrame = async () => {
const result = await addFrame();
if (result) {
console.log('Frame added:', result.url, result.token);
}
};
```
**Returns:**
```tsx
() => Promise<{
url: string;
token: string;
} | null>
```
### useNotification
This hook allows sending notifications to users who have added your frame. It requires a token and URL, which are returned when a user adds your frame.
```tsx
const sendNotification = useNotification();
// Usage
const handleSendNotification = () => {
sendNotification({
title: 'New High Score!',
body: 'Congratulations on your new high score!'
});
};
```
:::info
Notifications require a backend proxy to avoid CORS restrictions. The CLI automatically sets up this proxy at `/api/notification`, but you can override this in the `MiniKitProvider`.
:::
### useOpenUrl
This hook wraps `sdk.actions.openUrl` and falls back to `window.open` when outside a frame context.
```tsx
const openUrl = useOpenUrl();
// Usage
```
### useClose
This hook wraps the `sdk.actions.close` functionality.
```tsx
const close = useClose();
// Usage
```
### usePrimaryButton
This hook accepts primary button options and a callback which will be called on click.
```tsx
usePrimaryButton(
{ text: 'Submit Score' },
() => {
// Handle button click
submitScore();
}
);
```
### useViewProfile
This hook wraps `sdk.actions.viewProfile`, accepting an FID but falling back to the client's FID.
```tsx
const viewMyProfile = useViewProfile(); // Uses client's FID
const viewUserProfile = useViewProfile(123456); // Uses specified FID
// Usage
```
### useAuthenticate
This hook allows users to sign in with Farcaster. It wraps the SDK's signIn message, adding a default nonce and verification.
```tsx
const { signIn } = useAuthenticate();
// Usage
const handleSignIn = async () => {
const result = await signIn({
domain: 'your-domain.com',
siweUri: 'https://your-domain.com/login'
});
if (result) {
// Handle successful authentication
console.log('Authenticated:', result);
}
};
```
:::info
Authentication requires additional setup utilizing an auth framework like next/auth or manually integrating session storage and route/component authentication.
:::
## CLI
The MiniKit CLI is the easiest way to get started. It automatically creates a sample application that integrates different parts of the SDK and some OnchainKit components.
```bash
npx create-onchain --mini
```
### Features
The CLI creates an application with:
1. **Frontend and Backend Integration**
- Complete setup for adding frames, webhooks, and notifications
- Uses upstash/redis for data storage (compatible with Vercel)
- Requires users to sign up for an upstash/redis account and add their key and URL to the .env file
:::info
The CLI creates both frontend and backend components to support adding frames, webhooks, and notifications. While a frontend-only option was considered, the ability to add frames and handle notifications requires backend support. If you don't need these features, you can easily remove the database and related routes after project creation.
:::
2. **Account Association Generation**
- Automatically generates valid account associations
- Configures the necessary environment variables
3. **.well-known/farcaster.json Configuration**
- Sets up the required configuration file:
```json
{
"accountAssociation": {
"header": "eyJmaWQiOjgxODAyNiwidHlwZSI6ImN1c3RvZHkiLCJrZXkiOiIweDU4YjU1MTNjMzk5OTYzMjU0MjMzMmU0ZTJlRDAyOThFQzFmRjE4MzEifQ",
"payload": "eyJkb21haW4iOiI4MGI2LTI2MDAtMWYxOC0yNGM5LTYxMDUtNS0wLTQtNzA2Lm5ncm9rLWZyZWUuYXBwIn0",
"signature": "MHhmOGQ1YzQyMmU3ZTZlMWNhMzU1ZmNmN2ZjYzFmYjMyZWRhZmEyNWU1NjJiMzlhYzE4OWNlMmM5ODU3Y2JjZWViNzlkZTk2ZjhiNTc5NzZjMDM2NzM4Y2UwYjhhOGQxZmMyZDFhYzA2NTdiZTU5N2VhZjFhZDE1ODBmMGQyYjJhODFi"
},
"frame": {
"version": "next",
"name": "MiniKit",
"iconUrl": "https://onchainkit.xyz/favicon/48x48.png?v4-19-24",
"splashImageUrl": "https://onchainkit.xyz/favicon/48x48.png?v4-19-24",
"splashBackgroundColor": "#000000",
"homeUrl": "https://your-domain.app/minikit"
}
}
```
4. **Notification Proxy**
- Automatically sets up a proxy route at `/api/notification`
- Used by the `useNotification` hook when sending notifications
5. **Webhooks**
- Implements webhooks using the Farcaster key registry contract for verification
- Allows applications to respond to events such as `FRAME_ADDED`
### Demo Application
The CLI also creates a demo snake game application that showcases:
- Buttons to add the frame and connect your wallet
- High score tracking with attestations using OnchainKit's `` component
- Score display using OnchainKit's `` components to resolve ENS names
- Notifications for high scores (rate limited to one every 30 seconds)
## Next Steps
Now that you have MiniKit set up, you can:
1. Explore the demo application to understand how the hooks work
2. Customize the application to fit your needs
3. Deploy your application to a hosting provider like Vercel
Enjoy building!
# MiniKit Quickstart
This guide shows you how to get started with MiniKit, the easist way to build mini apps on Base! It can also be used to update an exisitng standalone app to a mini app. We'll start by setting up the template project with the CLI tool and then explore both built-in and additional features of MiniKit.
## Prerequisites
Before you begin developing with MiniKit, you'll need:
1. **Farcaster Account**: Create an account on [Warpcast](https://warpcast.com/) to test and deploy your Mini Apps.
2. **Coinbase Developer Platform Account** (Optional): Sign up for a [Coinbase Developer Platform](https://www.coinbase.com/en-nl/developer-platform) account if you need CDP API key for additional functionalities.
## What is a Mini App?
A mini app is a lightweight web app that runs directly inside [Farcaster Frames](https://docs.farcaster.xyz/developers/frames/v2/), without needing to open a browser or download anything. Built using familiar tools like Next.js and minikit, mini apps behave just like normal apps — but launch instantly from posts, making them feel native to the Farcaster experience.
## Initial Setup
:::steps
## Create a new MiniKit project using the CLI:
```bash
npx create-onchain --mini
```
## When prompted, enter your CDP Client API key.
You can get a CDP API key by going to the (CDP Portal)[portal.cdp.coinbase.com] and navigating API Keys -> Client API Key.
## Skip Frames Account Manifest Setup
You will be asked if you'd like to set up your manifest. You can skip the manifest setup step as we'll handle that separately once we know our project's URL.
## Navigate to your project directory and install dependencies:
```bash [Terminal]
cd your-project-name
npm install
npm run dev
```
:::
## Testing Your Mini App
To test your Mini App in Warpcast, you'll need a live URL.
We recommend using [Vercel](https://vercel.com) to deploy your MiniKit app, as it integrates seamlessly with the upstash/redis backend required for stateful frames, webhooks, and notifications.
Alternatively, you can use ngrok to tunnel your localhost to a live url.
::::details[Using ngrok]
:::warning[Pitfalls]
To successfully test your app, you'll need the paid version of ngrok. The free veresion has an approval screen which can break the frame manifest. Also the url for the free version will change every time requiring you to update the manifest each time you start a new ngrok tunnel.
:::
1. Start your development server:
```bash [Terminal]
npm run dev
```
2. Install and start ngrok to create a tunnel to your local server:
```bash [Terminal]
# Install ngrok if you haven't already
npm install -g ngrok
# Create a tunnel to your local server (assuming it's running on port 3000)
ngrok http 3000
```
3. Copy the HTTPS URL provided by ngrok (e.g. `https://your-tunnel.ngrok.io`)
4. Visit [Warpcast Frames Developer Tools](https://warpcast.com/~/developers/frames)
5. In the "Preview Frames" section, paste your ngrok URL to test your mini app.
::::
### Deploying to Vercel
:::steps
#### Install Vercel CLI: `npm install -g vercel`
#### Deploy with the command: `vercel`
#### Set environment variables in your Vercel project settings (you can use `vercel env add` to set these up via CLI):
- NEXT_PUBLIC_CDP_CLIENT_API_KEY (from [CDP Portal](https://portal.cdp.coinbase.com))
- NEXT_PUBLIC_URL (deployed app URL)
- NEXT_PUBLIC_IMAGE_URL (optional)
- NEXT_PUBLIC_SPLASH_IMAGE_URL (optional)
- NEXT_PUBLIC_SPLASH_BACKGROUND_COLORs
:::
You can now test your mini app:
1. Copy your deployed vercel URL
2. Visit [Warpcast Frames Developer Tools](https://warpcast.com/~/developers/frames) on web or mobile
3. Paste URL into "Preview Frames"
4. Tap Launch
## Exploring Built-in Features
The template comes with several pre-implemented features. Let's explore where they are and how they work.
### MiniKitProvider
The `MiniKitProvider` is set up in your `providers.tsx` file. It wraps your application to handle initialization, events, and automatically applie client safeAreaInsets to ensure your app doesn't overlap parent application elements.
```tsx [app/providers.tsx]
import { MiniKitProvider } from '@coinbase/onchainkit/minikit';
export function Providers(props: { children: ReactNode }) {
return (
{props.children}
);
}
```
The MiniKitProvider also sets up your wagmi and react-query providers automatically, elimintaing that initial setup work.
### useMiniKit
The `useMiniKit` hook is implemented in your main page component (`app/page.tsx`). It handles initialization of the frame and provides access to the SDK context.
```tsx [app/page.tsx]
const { setFrameReady, isFrameReady, context } = useMiniKit();
// The setFrameReady() function is called when your mini-app is ready to be shown
useEffect(() => {
if (!isFrameReady) {
setFrameReady();
}
}, [setFrameReady, isFrameReady]);
```
### Creating the Manifest
The Frame Manifest is required in order for users to save the frame to their account. This means its also required to send notifications to the user. We initially skipped this step when setting up the app. Now that we know our vercel url, we can configure our manifest.
To set up the manifest, run the following in your Terminal
```bash [Terminal]
npx create-onchain --manifest
```
Enter `y` to proceed with the setup and your browser will open to the following page:
The wallet that you connect must be your Farcaster custody wallet. You can import this wallet to your prefered wallet using the recovery phrase. You can find your recovery phrase in the Warpcast app under Settings -> Advanced -> Farcster recovery phrase.
Once connected, add the vercel url and sign the manifest. This will automatically update your .env variables locally, but we'll need to update Vercel's .env variables.
Create the following new .env variables in your vercel instance and paste the value you see in your local.env file
- FARCASTER_HEADER
- FARCASTER_PAYLOAD
- FARCASTER_SIGNATURE
Now that the manifest is correctly set up, the Save Frame button in the template app should work. We'll explore that below.
### useAddFrame
The `useAddFrame` hook is used to add your mini app to the user's list of mini apps. It's implemented in your main page component and displays a button in the top right allowing the user to add the mini app to their list.
When a user adds the mini app, it returns a url and token, which is used for sending the user notifications. For this walkthrough we'll simply console.log those results to use them later when setting up notifications.
```tsx [app/page.tsx]
const addFrame = useAddFrame()
// Usage in a button click handler
const handleAddFrame = async () => {
const result = await addFrame()
if (result) {
console.log('Frame added:', result.url, result.token)
}
}
```
:::warning[Not for Production]
In production, you'll want to save the url and token associated with each user in a persistent database so that you can send them notifications over time.
:::
### useOpenUrl
The `useOpenUrl` hook is used to open external URLs from within the frame. In the template, its used in the footer button which links to the MiniKit page.
```tsx [app/page.tsx]
const openUrl = useOpenUrl()
// Usage in a button click handler
// Then in the return function
```
Now that we've reviewed the MiniKit teamplate and the functionality already implemented, lets add some additional MiniKit features.
## Additional MiniKit Features
Now, let's implement additional hooks provided by the MiniKit library. We'll add these features one by one.
### `useClose`
First, let's add the ability to close the frame from within the interface:
```tsx [app/page.tsx]
// Add useClose to the import list
import { useMinikit, useAddFrame, useOpenUrl, useClose } from '@coinbase/onchainkit/minikit'
// Add the hook
const close = useClose()
// Add the button in the header right after the `saveFrameButton`
{saveFrameButton}
```
If you reload the frame in the Warpcast dev tools preview, you'll now see the close button in the top right.
### `usePrimaryButton`
The Primary Button is a button that always exists at the bottom of the frame. Its good for managing global state which is relevant throughout your mini app.
For the template example, we'll use the Priamry Button to Pause and Restart the game. The game state is managed within the `snake.tsx` component, and we can easily add the `usePrimaryButton` hook there since the MiniKit hooks are available throughout the app.
```tsx [/app/components/snake.tsx]
// add an import for usePrimaryButton
import {usePrimaryButton } from '@coinbase/onchainkit/minikit'
// game state already exists, so we'll leverage that below.
usePrimaryButton(
{text: gameState == GameState.RUNNING ? 'PAUSE GAME' : 'START GAME'},
() => {
setGameState(gameState == GameState.RUNNING ? GameState.PAUSED : GameState.RUNNING);
}
)
```
You'll notice that adding the Primary button takes up space at the bottom of the frame, which causes the "BUILT ON BASE WITH MINIKIT" button to move upwards and overlap with the contorls.
We can quickly fix that by changing the text to "BUILT WITH MINIKIT" and removing the `ml-4` style in the `className` of the `