• Mon. May 20th, 2024

How to Build a Farcaster Frame? A Step-by-Step Tutorial (Next JS)

Farcaster is a revolutionary platform that brings a new dimension to social interactions. It offers an ecosystem where users can interact with each other more dynamically and engagingly. One of the unique features of Farcaster is its API, which allows developers to create interactive applications within the Farcaster ecosystem.

Farcaster Frames: Interactive In-Feed Apps

A recent addition to the Farcaster platform, Frames is an innovative feature that transforms the way users interact on their social feeds. Instead of clicking on a link and being redirected, users can now interact with applications within their social feed. This means they can perform actions, such as using an app, minting an NFT and even tracking crypto prices without leaving their feed. This interactive in-feed app enhances the user experience by making it more seamless and engaging, while keeping users within the platform.

In today’s guide, we’ll be walking through how to build a Farcaster Frame using CoinGecko API’s trending pools data. Let’s jump in!


Prerequisites

To follow along with this tutorial, make sure you have the following installed:

  • CoinGecko API: We’ll use this to fetch onchain DEX endpoints to get data for the top trending crypto pools. As this is a paid exclusive endpoint, you’ll need to minimally be subscribed to the Analyst API plan. Ensure you have your Pro API key on hand.
  • Node.js and npm: Node.js is a JavaScript runtime that lets you run JavaScript on your server or computer. npm is a package manager for Node.js. You can download both from the official Node.js website.
  • Text Editor or IDE: You’ll need a text editor or an Integrated Development Environment (IDE) to write your code. Some popular choices include Sublime Text, Atom, Visual Studio Code, and PyCharm. For this tutorial, we’ll use Visual Studio Code.
  • Vercel: You will need to create a Vercel account to publicly deploy our frames and do the testing
  • Warpcast and Neynar account: You’ll need an account on Warpcast to test the app. Also, you’ll need a Neynar account API key.

OpenGraph: Enhancing Social Media Sharing

To enhance your Next.js application’s visibility on social media, I recommend incorporating OpenGraph meta tags. These tags help dictate how your content is displayed when shared, making it more appealing and shareable, and allows for richer previews of shared content, including titles, descriptions, and images. Here’s a sample code snippet:

<meta property="og:title" content="Title Here" />
<meta property="og:description" content="Description Here" />
<meta property="og:image" content="Image URL Here" />

Creating a Next.js App

Next.js is a popular framework for building React applications. It supports server-side rendering (SSR), which improves performance and SEO. Here are the steps to create a Next.js app in Visual Studio Code:

  1. Open Visual Studio Code.
  2. Open the terminal (View -> Terminal).
  3. Run npx create-next-app@latest.

Finally, let’s dive into the actual code.

Page.tsx

This code is part of a Next.js application. It’s written in TypeScript and is meant to be placed in a page.tsx file. The code is responsible for creating a page that displays a Farcaster Frame powered by CoinGecko.

  1. Importing necessary modules and types: The code starts by importing the necessary modules and types. getFrameMetadata is a function from the @coinbase/onchainkit package that helps generate metadata for a Farcaster Frame. Metadata is a type imported from ‘next’ that defines the shape of the metadata object.

  2. Defining frame metadata: The frameMetadata constant is an object that contains the metadata for the Farcaster Frame. This includes the buttons that will be displayed on the frame, the image that will be used, and the URL that will be posted when a button is clicked.

  3. Defining page metadata: The metadata constant is an object that contains the metadata for the page. This includes the base URL, the title and description of the page, and the OpenGraph data. The other property of the metadata object is spread with the frameMetadata object, which means all properties of frameMetadata are included in the metadata object.

  4. Exporting the page component: Finally, the Page component is exported. This is a functional component that returns a JSX element. In this case, it’s a simple heading welcoming users to the page.

The getFrameMetadata function is important because it generates the necessary metadata for a Farcaster Frame. This metadata is used by Farcaster to correctly display the frame within the social feed.

The export const metadata: Metadata = {...} line is crucial because it exports the metadata for the page. This metadata is used by Next.js for server-side rendering and by search engines and social media platforms for displaying rich previews of the page. It’s also used by Farcaster to display the frame within the social feed. The Metadata type ensures that the metadata object has the correct shape.

trendingPools/route.ts

This code is part of a Next.js serverless function. It’s written in TypeScript and is meant to be placed in an API route file. The code is responsible for handling POST requests and returning a Farcaster Frame powered by CoinGecko.

  1. Importing necessary modules and types: The code starts by importing the necessary modules and types. FrameRequest, getFrameMessage, and getFrameHtmlResponse are functions from the @coinbase/onchainkit package that help generate and validate Farcaster Frames. NextRequest and NextResponse are types imported from ‘next/server’ that define the shape of the request and response objects.

  2. Defining the getResponse function: The getResponse function is an asynchronous function that takes a NextRequest object and returns a NextResponse object. It starts by initializing several variables and then validates the request body using the getFrameMessage function.

  3. Fetching data from CoinGecko: If the request is valid, the function fetches data from the CoinGecko API and processes it. It then uses this data to generate chart options and fetches a chart image from the QuickChart API.

  4. Handling button clicks: If the second button is clicked, the function redirects the user to the CoinGecko website. Otherwise, it generates a Farcaster Frame with the chart image and returns it as a response.

  5. Error handling: If an error occurs at any point, the function returns an error image.

  6. Exporting the POST function: Finally, the POST function is exported. This function simply calls the getResponse function with the request object and returns its result.

The getFrameMessage function is important because it validates the request body and extracts the message from it. This message contains information about any buttons that were clicked in the Farcaster Frame.

The export const dynamic = 'force-dynamic'; line is crucial because it tells Next.js to always render this page on the server, regardless of whether it could be statically optimized. This is necessary because the content of the page depends on the request body, which can only be accessed on the server.

Running the Next.js Application Locally

To run your Next.js application locally, follow these steps:

  1. Open Terminal: Open a terminal window on your computer.

  2. Navigate to Your Project Directory: Use the cd command to navigate to your project directory. For example, if your project is in a folder called my-next-app, you would type cd my-next-app.

  3. Install Dependencies: If you haven’t already, install the project’s dependencies by running npm install.

  4. Start the Development Server: Start the Next.js development server by running npm run dev. This will start the server on localhost:3000 (unless you’ve configured a different port).

Now, you can open your web browser and navigate to http://localhost:3000 to see your application running.

Running Farcaster Frames Tests Locally

To run Farcaster Frames tests locally using the OnChainKit, follow these steps:

  1. Clone the OnChainKit Repository: First, you need to clone the OnChainKit repository from GitHub. You can do this by running git clone https://github.com/coinbase/onchainkit.git in your terminal.

  2. Navigate to the Framegear Directory: The tests for Farcaster Frames are located in the framegear directory within the OnChainKit repository. Navigate to this directory by running cd onchainkit/framegear.

  3. Install Dependencies: Install the project’s dependencies by running npm install.

  4. Run the Tests: Finally, run the tests by executing npm run dev which will start the application on ‘http://localhost:1337’ and you can paste your application url http://localhost:3000 to the frames validator to test this

Remember, running tests is a crucial part of the development process. It helps you catch and fix issues before they affect your users. So, take your time, test thoroughly, and ensure your Farcaster Frame works perfectly.

Deploying the Application on Vercel

Once you’ve tested your application and are satisfied with its functionality, the next step is to deploy it. Vercel is a popular platform for deploying Next.js applications. Here’s how you can deploy your application using Vercel:

  1. Push Your Changes to GitHub: First, make sure all your changes are committed and pushed to your GitHub repository. If you haven’t already, initialize a Git repository in your project directory, commit your changes, and push them to GitHub.

git init

git add .

git commit -m "Initial commit"

git remote add origin https://github.com/yourusername/yourrepository.git

git push -u origin master

  1. Connect Your GitHub Repository to Vercel: Next, go to the Vercel dashboard and click on the “Import Project” button. You’ll be asked to provide the URL of your GitHub repository. Enter the URL and click “Continue”.

  2. Configure Your Project: On the next page, you’ll be asked to configure your project. You can leave the settings at their defaults for most Next.js projects. Click “Deploy” when you’re done.

  3. Wait for Your Project to Deploy: Vercel will now deploy your project. This may take a few minutes. Once the deployment is complete, Vercel will provide you with a URL where you can access your deployed application.

  4. Test Your Deployed Application: Finally, navigate to the provided URL and test your application to make sure everything works as expected.

Remember, every time you push changes to your GitHub repository, Vercel will automatically redeploy your application. So, you can easily update your application by simply pushing your changes to GitHub.

Testing the Application on Warpcast

Once you’ve set up your application and written your code, it’s important to test it to ensure everything is working as expected. Warpcast provides a playground for developers to test their Farcaster Frames. Here’s how you can test your application using Warpcast:

  1. Navigate to the Warpcast Developer Playground: Open your web browser and navigate to https://warpcast.com/~/developers/frames. This is the Warpcast Developer Playground where you can test your Farcaster Frames.

  2. Enter Your Frame URL: In the “Frame URL” field, enter the URL of your Next.js serverless function. This is the URL where your serverless function is hosted and where Warpcast will send POST requests.

  3. Send a Test Request: Click the “Send Test Request” button. This will send a POST request to your serverless function with a test message. The response from your serverless function will be displayed in the Farcaster Frame in the playground.

  4. Inspect the Result: Look at the Farcaster Frame in the playground. It should display the result of your serverless function. If there are any errors, they will be displayed here.

  5. Iterate: If you notice any issues or if the Frame doesn’t behave as expected, go back to your code, make the necessary adjustments, and test again. Repeat this process until you’re satisfied with the result.

💡Pro-tip: Testing is a crucial part of the development process. It helps you catch and fix issues before they affect your users.

Cast Farcaster Frames in Warpcast

Now its the time to see the magic! To display your app as a Frame in Warpcast, you need to create a new post (also known as a “cast”) and embed the URL of your app in it. Here’s how you can do it:

  1. Log in to Warpcast: Open your web browser and navigate to Warpcast. Make sure you’re logged into your account.

  2. Create a New Cast: On the Warpcast platform, click on the “Create Cast” button to start creating a new cast.

  3. Embed Your App URL: In the cast creation form, there’s a field where you can embed a URL. Enter the URL of your deployed Next.js application (https://your-crypto-app.vercel.app/) in this field.

  4. Publish Your Cast: Once you’ve filled out the rest of the cast creation form to your liking, click the “Cast” button. Your cast is now live on Warpcast!

  5. Interact with Your Frame: Navigate to your social feed on Warpcast. You should see your newly published cast in your feed. If you click on it, it will open up your Farcaster Frame.

A Frame is a micro application based on HTML that runs within a Farcaster post. When you interact with a Frame, your Farcaster ID and linked wallet address are used as metadata to customize your experience. Enjoy the interactive experience that Farcaster Frames brings to Warpcast!


Advanced Functionalities and Useful Endpoints

While the tutorial above covers the basic development of a Farcaster Frame application, developers who might want to explore other Farcaster Frame functionalities can consider the following:

  • Cryptocurrency Price Converter: Implement a feature that allows users to convert different cryptocurrencies or between fiat and cryptocurrencies. Users can enter a ticker and an amount, and the Frame will display the converted amount. This feature can be built using the Coin Price by IDs endpoint from the CoinGecko API.

  • Display BTC:ETH Dominance: Create a button that, when clicked, displays the dominance of Bitcoin (BTC) over Ethereum (ETH). This can be achieved by using the Global Market Cap Charts endpoint from the CoinGecko API.

  • Real-Time Price Updates: Allow users to fetch live crypto prices for their specified crypto assets. Similarly, this would involve interacting with the Coin Price by IDs endpoint. Real-time price updates can help users make timely investment decisions.

Developing advanced features require familiarizing yourself with the API documentation, understanding the various endpoints you’ll be interacting with, and the specific data each endpoint provides. Always prioritize the accuracy of your app’s data and adhere to best practices in the crypto industry.

 


 

Conclusion

 

Developing a Farcaster Frame application opens up a world of possibilities for interactive social media experiences. By leveraging the power of CoinGecko’s comprehensive cryptocurrency API, we can create dynamic Frames right within the Farcaster ecosystem. Whether you’re a seasoned developer or just starting out, the steps outlined in this tutorial will guide you in creating your own Farcaster Frame application. Remember, the key to a great Frame is a combination of useful functionality, seamless user experience, and engaging interactivity. Happy coding!

 


 

Interested in similar guides that leverage real-time, on-chain DEX data? Check out this developer tutorial that covers how to build a DEX tracker on Streamlit.