Flow App Quickstart
Last Updated: January 11th 2022
Note: This page will walk you through a very bare bones project to get started building a web3 dapp using the Flow Client Library (FCL). If you are looking for a clonable repo, check out the scaffolds availabe in the Flow CLI.
Video Walkthrough
Below is a video walkthrough covering the contents of this tutorial. You are welcome to watch or skip the video walkthrough depending on your style of learning.
Before You Start
Make sure you have Flow CLI installed. If you don't, follow the installation instructions.
Introduction
FCL-JS is the easiest way to start building decentralized applications. FCL (aka Flow Client Library) wraps much of the logic you'd have to write yourself on other blockchains. Follow this quick start and you'll have a solid overview of how to build a shippable dapp on Flow.
We're going to make an assumption that you know or understand React; however, the concepts should be easy to understand and transfer to another framework. While this tutorial will make use of Cadence (Flow's smart contract language), you do not need to know it. Instead, we recommend later diving into learning the Cadence language once you've gotten the core FCL concepts down.
In this tutorial, we are going to interact with an existing smart contract on Flow's testnet known as the Profile Contract. Using this contract, we will create a new profile and edit the profile information, both via a wallet. In order to do this, the FCL concepts we'll cover are:
- Installation
- Configuration
- Authentication
- Querying the Blockchain
- Initializing an Account
- Mutating the Blockchain
And if you ever have any questions we're always happy to help on Discord. There are also links at the end of this article for diving deeper into building on Flow.
Installation
The first step is to generate a React app using Next.js and create-next-app. From your terminal, run the following:
_10npx create-next-app@latest flow-app_10cd flow-app
Configuration
Setting up Flow
Then, using the Flow CLI, create a new flow.json file in the root of your app. This file will contain the Flow configuration for your project.
_10flow init
We don't recommend keeping private keys in your flow.json, so for good practice let's move our private key to a emulator.key file in the root of our project and point to it using the key/location pattern used by Flow CLI. This file will be ignored by git, so it won't be committed to your repository.
We won't be using emulator and running contracts locally in this quickstart, but FCL will complain if it finds private keys in your flow.json file.
Your flow.json file should look like this:
_17{_17	"networks": {_17		"emulator": "127.0.0.1:3569",_17		"mainnet": "access.mainnet.nodes.onflow.org:9000",_17		"sandboxnet": "access.sandboxnet.nodes.onflow.org:9000",_17		"testnet": "access.devnet.nodes.onflow.org:9000"_17	},_17	"accounts": {_17		"emulator-account": {_17			"address": "f8d6e0586b0a20c7",_17			"key": {_17				"type": "file",_17				"location": "./emulator.key"_17			}_17		}_17	}_17}
Configuring FCL
Next, install FCL so we can use it in our app.
_10npm install @onflow/fcl --save
Now run the app using the following command in your terminal.
_10npm run dev
Now that your app is running, you can configure FCL. Within the main project directory, create a folder called flow and create a file called config.js. This file will contain configuration information for FCL, such as what Access Node and wallet discovery endpoint to use (e.g. testnet or a local emulator). Add the following contents to the file:
Note: These values are required to use FCL with your app.
Create file:
./flow/config.js
_10import { config } from "@onflow/fcl";_10_10config({_10  "accessNode.api": "https://rest-testnet.onflow.org", // Mainnet: "https://rest-mainnet.onflow.org"_10  "discovery.wallet": "https://fcl-discovery.onflow.org/testnet/authn" // Mainnet: "https://fcl-discovery.onflow.org/authn"_10})
📣 Tip: It's recommend to replace these values with environment variables for easy deployments across different environments like development/production or Testnet/Mainnet.
The accessNode.api key specifies the address of a Flow access node. Flow provides these, but in the future access to Flow may be provided by other 3rd parties, through their own access nodes.
discovery.wallet is an address that points to a service that lists FCL compatible wallets. Flow's FCL Discovery service is a service that FCL wallet providers can be added to, and be made 'discoverable' to any application that uses the discovery.wallet endpoint.
Learn more about configuring Discovery or setting configuration values.
The main page for Next.js apps is located in pages/index.js. So let's finish configuring our dapp by going in the pages/ directory and importing the config file into the top of our index.js file. We'll then swap out the default component in index.js to look like this:
Replace file:
./pages/index.js
_20import "../flow/config";_20_20import Head from 'next/head'_20_20export default function Home() {_20  return (_20    <div>_20      <Head>_20        <title>FCL Quickstart with NextJS</title>_20        <meta name="description" content="My first web3 app on Flow!" />_20        <link rel="icon" href="/favicon.png" />_20      </Head>_20_20      <main>_20        Hello World_20      </main>_20_20    </div>_20  )_20}
Now we're ready to start talking to Flow!
Authentication
To authenticate a user, all an app has to do is call fcl.logIn(). Sign up and unauthenticate are all also as simple as fcl.signUp() and fcl.unauthenticate().  Once authenticated, FCL sets an object called fcl.currentUser which exposes methods for watching changes in user data, signing transactions, and more. For more information on the currentUser, read more here.
Let's add in a few buttons for sign up/login and also subscribe to changes on the currentUser. When the user is updated (which it will be after authentication), we'll set the user state in our component to reflect this. To demonstrate user authenticated sessions, we'll conditionally render a component based on if the user is or is not logged in.
This is what your file should look like now:
Replace file:
./pages/index.js
_44import Head from 'next/head'_44import "../flow/config";_44import { useState, useEffect } from "react";_44import * as fcl from "@onflow/fcl";_44_44export default function Home() {_44_44  const [user, setUser] = useState({loggedIn: null})_44_44  useEffect(() => fcl.currentUser.subscribe(setUser), [])_44_44  const AuthedState = () => {_44    return (_44      <div>_44        <div>Address: {user?.addr ?? "No Address"}</div>_44        <button onClick={fcl.unauthenticate}>Log Out</button>_44      </div>_44    )_44  }_44_44  const UnauthenticatedState = () => {_44    return (_44      <div>_44        <button onClick={fcl.logIn}>Log In</button>_44        <button onClick={fcl.signUp}>Sign Up</button>_44      </div>_44    )_44  }_44_44  return (_44    <div>_44      <Head>_44        <title>FCL Quickstart with NextJS</title>_44        <meta name="description" content="My first web3 app on Flow!" />_44        <link rel="icon" href="/favicon.png" />_44      </Head>_44      <h1>Flow App</h1>_44      {user.loggedIn_44        ? <AuthedState />_44        : <UnauthenticatedState />_44      }_44    </div>_44  );_44}
You should now be able to log in or sign up a user and unauthenticate them. Upon logging in or signing up your users will see a popup where they can choose between wallet providers. Let's select the Blocto wallet for this example to create an account. Upon completing authentication, you'll see the component change and the user's wallet address appear on the screen if you've completed this properly.
Querying the Blockchain
One of the main things you'll often need to do when building a dapp is query the Flow blockchain and the smart contracts deployed on it for data. Since smart contracts will live on both Testnet and Mainnet, let's put the account address where the smart contract lives into the flow.json so FCL can pick it up. We are going to also use an alias for testnet.
If you want to see how to use local files for emulator and learn more about aliases, check out the flow.json documentation. For now, know that an alias lets us specify a contract address based on a specific network (e.g. testnet/mainnet).
Replace file:
flow.json
_24{_24	"contracts": {_24		"Profile": {_24			"aliases": {_24				"testnet": "0xba1132bc08f82fe2"_24			}_24		}_24	},_24	"networks": {_24		"emulator": "127.0.0.1:3569",_24		"mainnet": "access.mainnet.nodes.onflow.org:9000",_24		"sandboxnet": "access.sandboxnet.nodes.onflow.org:9000",_24		"testnet": "access.devnet.nodes.onflow.org:9000"_24	},_24	"accounts": {_24		"emulator-account": {_24			"address": "f8d6e0586b0a20c7",_24			"key": {_24				"type": "file",_24				"location": "./emulator.key"_24			}_24		}_24	}_24}
If you want to see the on chain smart contract we'll be speaking with next, you can view the Profile Contract source code but again for this tutorial it's not necessary you understand it.
First, lets query the contract to see what the user's profile name is.
A few things need to happen in order to do that:
- We need to import the contract and pass it the user's account address as an argument.
- Execute the script using fcl.query.
- Set the result of the script to the app state in React so we can display the profile name in our browser.
- Display "No Profile" if one was not found.
Take a look at the new code. We'll explain each new piece as we go. Remember, the cadence code is a separate language from JavaScript used to write smart contracts, so you don't need to spend too much time trying to understand it. (Of course, you're more than welcome to, if you want to!)
Replace file:
./pages/index.js
_63import Head from 'next/head'_63import "../flow/config";_63import { useState, useEffect } from "react";_63import * as fcl from "@onflow/fcl";_63_63export default function Home() {_63_63  const [user, setUser] = useState({loggedIn: null})_63  const [name, setName] = useState('') // NEW_63_63  useEffect(() => fcl.currentUser.subscribe(setUser), [])_63_63	// NEW_63  const sendQuery = async () => {_63    const profile = await fcl.query({_63      cadence: `_63        import Profile from 0xProfile_63_63        pub fun main(address: Address): Profile.ReadOnly? {_63          return Profile.read(address)_63        }_63      `,_63      args: (arg, t) => [arg(user.addr, t.Address)]_63    })_63_63    setName(profile?.name ?? 'No Profile')_63  }_63_63  const AuthedState = () => {_63    return (_63      <div>_63        <div>Address: {user?.addr ?? "No Address"}</div>_63        <div>Profile Name: {name ?? "--"}</div> {/* NEW */}_63        <button onClick={sendQuery}>Send Query</button> {/* NEW */}_63        <button onClick={fcl.unauthenticate}>Log Out</button>_63      </div>_63    )_63  }_63_63  const UnauthenticatedState = () => {_63    return (_63      <div>_63        <button onClick={fcl.logIn}>Log In</button>_63        <button onClick={fcl.signUp}>Sign Up</button>_63      </div>_63    )_63  }_63_63  return (_63    <div>_63      <Head>_63        <title>FCL Quickstart with NextJS</title>_63        <meta name="description" content="My first web3 app on Flow!" />_63        <link rel="icon" href="/favicon.png" />_63      </Head>_63      <h1>Flow App</h1>_63      {user.loggedIn_63        ? <AuthedState />_63        : <UnauthenticatedState />_63      }_63    </div>_63  );_63}
A few things happened. In our AuthedState component, we added a button to send a query for the user's profile name and a div to display the result above it. The corresponding useState initialization can be seen at the top of the component.
The other thing we did is build out the actual query inside of sendQuery method. Let's take a look at it more closely:
_10await fcl.query({_10  cadence: `_10    import Profile from 0xProfile_10_10    pub fun main(address: Address): Profile.ReadOnly? {_10      return Profile.read(address)_10    }_10  `,_10  args: (arg, t) => [arg(user.addr, t.Address)]_10});
Inside the query you'll see we set two things: cadence and args. Cadence is Flow's smart contract language we mentioned. For this tutorial, when you look at it you just need to notice that it's importing the Profile contract from the account we named 0xProfile earlier in our config file, then also taking an account address, and reading it. That's it until you're ready to learn more Cadence.
In the args section, we are simply passing it our user's account address from the user we set in state after authentication and giving it a type of Address.  For more possible types, see this reference.
Go ahead and click the "Send Query" button. You should see "No Profile." That's because we haven't initialized the account yet.
Initializing the Account
For the Profile contract to store a Profile in a user's account, it does so by initializing what is called a "resource." A resource is an ownable piece of data and functionality that can live in the user's account storage. This paradigm is known is as "resource-oriented-programming", a principle that is core to Cadence and differentiates its ownership model from other smart contract languages, read more here. Cadence makes it so that resources can only exist in one place at any time, they must be deliberately created, cannot be copied, and if desired, must be deliberately destroyed.
There's a lot more to resources in Cadence than we'll cover in this guide, so if you'd like to know more, check out this Cadence intro.
To do this resource initialization on an account, we're going to add another function called initAccount. Inside of that function, we're going to add some Cadence code which says, "Hey, does this account have a profile? If it doesn't, let's add one." We do that using something called a "transaction." Transactions occur when you want to change the state of the blockchain, in this case, some data in a resource, in a specific account. And there is a cost (transaction fee) in order to do that; unlike a query.
That's where we jump back into FCL code. Instead of query, we use mutate for transactions. And because there is a cost, we need to add a few fields that tell Flow who is proposing the transaction, who is authorizing it, who is paying for it, and how much they're willing to pay for it. Those fields — not surprisingly — are called: proposer, authorizer, payer, and limit. For more information on these signatory roles, check out this doc.
Let's take a look at what our account initialization function looks like:
_27const initAccount = async () => {_27  const transactionId = await fcl.mutate({_27    cadence: `_27      import Profile from 0xProfile_27_27      transaction {_27        prepare(account: AuthAccount) {_27          // Only initialize the account if it hasn't already been initialized_27          if (!Profile.check(account.address)) {_27            // This creates and stores the profile in the user's account_27            account.save(<- Profile.new(), to: Profile.privatePath)_27_27            // This creates the public capability that lets applications read the profile's info_27            account.link<&Profile.Base{Profile.Public}>(Profile.publicPath, target: Profile.privatePath)_27          }_27        }_27      }_27    `,_27    payer: fcl.authz,_27    proposer: fcl.authz,_27    authorizations: [fcl.authz],_27    limit: 50_27  })_27_27  const transaction = await fcl.tx(transactionId).onceSealed()_27  console.log(transaction)_27}
You can see the new fields we talked about. You'll also notice fcl.authz. That's shorthand for "use the current user to authorize this transaction", (you could also write it as fcl.currentUser.authorization). If you want to learn more about transactions and signing transactions, you can view the docs here. For this example, we'll keep it simple with the user being each of these roles.
You'll also notice we are awaiting a response with our transaction data by using the syntax fcl.tx(transactionId).onceSealed(). This will return when the blockchain has sealed the transaction and it's complete in processing it and verifying it.
Now your index.js file should look like this (we also added a button for calling the initAccount function in the AuthedState):
Replace file:
./pages/index.js
_92import Head from 'next/head'_92import "../flow/config";_92import { useState, useEffect } from "react";_92import * as fcl from "@onflow/fcl";_92_92export default function Home() {_92_92  const [user, setUser] = useState({loggedIn: null})_92  const [name, setName] = useState('')_92_92  useEffect(() => fcl.currentUser.subscribe(setUser), [])_92_92  const sendQuery = async () => {_92    const profile = await fcl.query({_92      cadence: `_92        import Profile from 0xProfile_92_92        pub fun main(address: Address): Profile.ReadOnly? {_92          return Profile.read(address)_92        }_92      `,_92      args: (arg, t) => [arg(user.addr, t.Address)]_92    })_92_92    setName(profile?.name ?? 'No Profile')_92  }_92_92  // NEW_92  const initAccount = async () => {_92    const transactionId = await fcl.mutate({_92      cadence: `_92        import Profile from 0xProfile_92_92        transaction {_92          prepare(account: AuthAccount) {_92            // Only initialize the account if it hasn't already been initialized_92            if (!Profile.check(account.address)) {_92              // This creates and stores the profile in the user's account_92              account.save(<- Profile.new(), to: Profile.privatePath)_92_92              // This creates the public capability that lets applications read the profile's info_92              account.link<&Profile.Base{Profile.Public}>(Profile.publicPath, target: Profile.privatePath)_92            }_92          }_92        }_92      `,_92      payer: fcl.authz,_92      proposer: fcl.authz,_92      authorizations: [fcl.authz],_92      limit: 50_92    })_92_92    const transaction = await fcl.tx(transactionId).onceSealed()_92    console.log(transaction)_92  }_92_92  const AuthedState = () => {_92    return (_92      <div>_92        <div>Address: {user?.addr ?? "No Address"}</div>_92        <div>Profile Name: {name ?? "--"}</div>_92        <button onClick={sendQuery}>Send Query</button>_92        <button onClick={initAccount}>Init Account</button> {/* NEW */}_92        <button onClick={fcl.unauthenticate}>Log Out</button>_92      </div>_92    )_92  }_92_92  const UnauthenticatedState = () => {_92    return (_92      <div>_92        <button onClick={fcl.logIn}>Log In</button>_92        <button onClick={fcl.signUp}>Sign Up</button>_92      </div>_92    )_92  }_92_92  return (_92    <div>_92      <Head>_92        <title>FCL Quickstart with NextJS</title>_92        <meta name="description" content="My first web3 app on Flow!" />_92        <link rel="icon" href="/favicon.png" />_92      </Head>_92      <h1>Flow App</h1>_92      {user.loggedIn_92        ? <AuthedState />_92        : <UnauthenticatedState />_92      }_92    </div>_92  )_92}
Press the "Init Account" button you should see the wallet ask you to approve a transaction. After approving, you will see a transaction response appear in your console (make sure to have that open). It may take a few moments. With the transaction result printed, you can use the transactionId to look up the details of the transaction using a block explorer.
Mutating the Blockchain
Now that we have the profile initialized, we are going to want to mutate it some more. In this example, we'll use the same smart contract provided to change the profile name.
To do that, we are going to write another transaction that adds some Cadence code which lets us set the name. Everything else looks the same in the following code except for one thing: we'll subscribe to the status changes instead of waiting for it to be sealed after the mutate function returns.
It looks like this:
_22const executeTransaction = async () => {_22  const transactionId = await fcl.mutate({_22    cadence: `_22      import Profile from 0xProfile_22_22      transaction(name: String) {_22        prepare(account: AuthAccount) {_22          account_22            .borrow<&Profile.Base{Profile.Owner}>(from: Profile.privatePath)!_22            .setName(name)_22        }_22      }_22    `,_22    args: (arg, t) => [arg("Flow Developer", t.String)],_22    payer: fcl.authz,_22    proposer: fcl.authz,_22    authorizations: [fcl.authz],_22    limit: 50_22  })_22_22  fcl.tx(transactionId).subscribe(res => setTransactionStatus(res.status))_22}
Here you can see our argument is "Flow Developer" and at the bottom we've called the subscribe method instead of onceSealed.
Let's see how that works inside our whole index.js file. But, let's also set the statuses to our React component's state so we can see on screen what state we're in.
Replace file:
./pages/index.js
_118import Head from 'next/head'_118import "../flow/config";_118import { useState, useEffect } from "react";_118import * as fcl from "@onflow/fcl";_118_118export default function Home() {_118_118  const [user, setUser] = useState({loggedIn: null})_118  const [name, setName] = useState('')_118  const [transactionStatus, setTransactionStatus] = useState(null) // NEW_118_118  useEffect(() => fcl.currentUser.subscribe(setUser), [])_118_118  const sendQuery = async () => {_118    const profile = await fcl.query({_118      cadence: `_118        import Profile from 0xProfile_118_118        pub fun main(address: Address): Profile.ReadOnly? {_118          return Profile.read(address)_118        }_118      `,_118      args: (arg, t) => [arg(user.addr, t.Address)]_118    })_118_118    setName(profile?.name ?? 'No Profile')_118  }_118_118  const initAccount = async () => {_118    const transactionId = await fcl.mutate({_118      cadence: `_118        import Profile from 0xProfile_118_118        transaction {_118          prepare(account: AuthAccount) {_118            // Only initialize the account if it hasn't already been initialized_118            if (!Profile.check(account.address)) {_118              // This creates and stores the profile in the user's account_118              account.save(<- Profile.new(), to: Profile.privatePath)_118_118              // This creates the public capability that lets applications read the profile's info_118              account.link<&Profile.Base{Profile.Public}>(Profile.publicPath, target: Profile.privatePath)_118            }_118          }_118        }_118      `,_118      payer: fcl.authz,_118      proposer: fcl.authz,_118      authorizations: [fcl.authz],_118      limit: 50_118    })_118_118    const transaction = await fcl.tx(transactionId).onceSealed()_118    console.log(transaction)_118  }_118_118  // NEW_118  const executeTransaction = async () => {_118    const transactionId = await fcl.mutate({_118      cadence: `_118        import Profile from 0xProfile_118_118        transaction(name: String) {_118          prepare(account: AuthAccount) {_118            account_118              .borrow<&Profile.Base{Profile.Owner}>(from: Profile.privatePath)!_118              .setName(name)_118          }_118        }_118      `,_118      args: (arg, t) => [arg("Flow Developer!", t.String)],_118      payer: fcl.authz,_118      proposer: fcl.authz,_118      authorizations: [fcl.authz],_118      limit: 50_118    })_118_118    fcl.tx(transactionId).subscribe(res => setTransactionStatus(res.status))_118  }_118_118  const AuthedState = () => {_118    return (_118      <div>_118        <div>Address: {user?.addr ?? "No Address"}</div>_118        <div>Profile Name: {name ?? "--"}</div>_118        <div>Transaction Status: {transactionStatus ?? "--"}</div> {/* NEW */}_118        <button onClick={sendQuery}>Send Query</button>_118        <button onClick={initAccount}>Init Account</button>_118        <button onClick={executeTransaction}>Execute Transaction</button> {/* NEW */}_118        <button onClick={fcl.unauthenticate}>Log Out</button>_118      </div>_118    )_118  }_118_118  const UnauthenticatedState = () => {_118    return (_118      <div>_118        <button onClick={fcl.logIn}>Log In</button>_118        <button onClick={fcl.signUp}>Sign Up</button>_118      </div>_118    )_118  }_118_118  return (_118    <div>_118      <Head>_118        <title>FCL Quickstart with NextJS</title>_118        <meta name="description" content="My first web3 app on Flow!" />_118        <link rel="icon" href="/favicon.png" />_118      </Head>_118      <h1>Flow App</h1>_118      {user.loggedIn_118        ? <AuthedState />_118        : <UnauthenticatedState />_118      }_118    </div>_118  )_118}
Now if you click the "Execute Transaction" button you'll see the statuses update next to "Transaction Status." When you see "4" that means it's sealed! Status code meanings can be found here. If you query the account profile again, "Profile Name:" should now display "Flow Developer".
That's it! You now have a shippable Flow dapp that can auth, query, init accounts, and mutate the chain. This is just the beginning. There is so much more to know. We have a lot more resources to help you build. To dive deeper, here are a few good places for taking the next steps:
Cadence
FCL Scaffolds
Full Stack NFT Marketplace Example
More FCL
- FCL API Quick Reference
- More on Scripts
- More on Transactions
- User Signatures
- Proving Account Ownership
Other