Skip to content

React Quickstart

Account Kit is the easiest way to integrate smart accounts in your React App. In this guide, we'll walk you through crafting a delightful sign-up with email and passkey, and then a seamless checkout with gas sponsorship.

For existing EOA (non-smart contract) users, the Account Kit modal also supports logging in with injected wallets!

Below you'll find guides for:

  1. Starting fresh with a new NextJS Template
  2. Integrate Account Kit in an existing React Project

New NextJS project

1. Create a new NextJS app using our template

For a simple end-to-end example, we will spin up a new NextJS app using the ui components template.

yarn
yarn create next-app my-smart-app -e https://github.com/avarobinson/embedded-accounts-ui-components-alpha-quickstart-nextjs

2. Get your Alchemy API Key

  1. Get your API key by creating a new app in your Alchemy Dashboard
  2. Create a new account config in your Alchemy Accounts Manager Dashboard
    1. Use http://localhost:3000 as the “Redirect URL” for testing (***make sure to set http NOT https for local testing) alchemy create new embedded account config highlighting where to set localhost
    2. Optionally, stylize ✨ the auth email with your brand color and logo!
    3. Apply the config to your app from step 1 apply your the config to the app from the first step
  3. Copy the API Key found at the end of the URL (you don't need the whole link for this demo) how to copy the api key

…and paste the API key into config.ts where you see your_api_key

config.ts
// ...other stuff in the file
export const config = createConfig(
  {
    apiKey: "your_api_key", // TODO: add your Alchemy API key - setup your app and embedded account config in the alchemy dashboard (https://dashboard.alchemy.com/accounts) - if you don't want to leak api keys, you can proxy to a backend and set the rpcUrl instead here
    chain: sepolia,
    ssr: true, // defers hydration of the account state to the client after the initial mount solving any inconsistencies between server and client state (read more here: https://accountkit.alchemy.com/react/ssr)
    storage: cookieStorage, // persist the account state using cookies (read more here: https://accountkit.alchemy.com/react/ssr#persisting-the-account-state)
  },
  uiConfig
);
// ...other stuff in the file

3. Run the app!

That's it! Run the NextJS app to see your new auth flow in action ✨

yarn
yarn dev

Existing project

To integrate in to your existing dapp and better understand the above demo app, we will walk through the each of the steps required for using alchemy ui components in technical depth!

1. Install the packages

Prerequisites Installation

Install the React and Infra packages from Account Kit along with tailwind for styling and react-query to support react components.

yarn
yarn add @account-kit/infra @account-kit/react @tanstack/react-query
yarn add -D tailwindcss postcss autoprefixer
Tailwind Setup

If you don't have tailwind setup yet, once you run the above, you can run the following:

npx tailwindcss init -p

The above command will generate a tailwind.config.ts and postcss.config.ts file for you. The only thing left to do is to create a global.css file and import it in the root of your app.

global.css
@tailwind base;
@tailwind components;
@tailwind utilities;

For more on tailwind setup, see these steps.

2. Get your Alchemy API Key

See the steps above in the NextJS section to get your API key.

3. Configure your UI components

In this step, you'll customize your authentication methods and UI styles.

The demo app provides an interactive sandbox to explore combinations. When you’re all done, click the ‘Code preview’ toggle to export your code! You’ll get two files:

  1. tailwind.config.ts
  2. config.ts

*Note: tailwind.config.ts and config.ts changes are required even if using default styling*

Customize styles and auth methods in the demo app

3a. Customize styling with tailwind

  1. In the demo app, copy your tailwind.config.ts code into the file of the same name in your project. This will apply your custom styles: colors, border radius, and illustrations.

    1. Logo: logo images are loaded client side for maximum performance, so you’ll need to add the image file to your project and specify the file path in the config where noted.
    2. Light/Dark mode:
      1. Light Mode and Dark Mode are set to match the system theme. You can manually override this by following this guide. TLDR: update your tailwindcss config to use selector mode for dark and then add the dark class to the root of your DOM
    3. You can customize even more style properties.
  2. Make sure you wrap your existing tailwind config with withAccountKitUi :

    tailwind.config.ts
    // tailwind.config.ts
    import { withAccountKitUi } from "@account-kit/react/tailwind";
     
    export default withAccountKitUi(
      {
        // 1. (required) your tailwind config generated in setup or existing config including content, theme, plugins, etc. - https://tailwindcss.com/docs/installation/using-postcss
      },
      {
        // 2. (optional) overwrite AccountKit theme
      }
    );

3b. Customize authentication methods

  1. In the root of your project, create a config.ts file

  2. In the demo app, copy your config.ts code into the file of the same name in your project. This will apply your authentication methods (email, passkey, etc.)

    • createConfig is used to initialize the alchemy provider in the next step. It requires 2 params:

      • props: for creating an Alchemy config. Notice the 4 params passed to props in our example:

        • apiKey (required): Copy-paste your Alchemy API key, from step 2. Note that for production this key should be protected by proxying to the backend and setting rpcUrl instead
        • chain (required): Chain imported from @account-kit/infra . This chain must match the chain your api key / embedded accounts config is setup for.
        • ssr (optional): Highly recommended for NextJs applications to keep account state consistent between the server and client
        • storage (optional): Cookie storage highly recommended for NextJs applications to persist and cache account state across page loads
      • ui: for creating Alchemy Accounts UI components

      • See here for full details on the ui config params including authentication options

  3. Make sure to export your config and queryClient:

Remember to paste in your API Key from step 2
src/config.ts
// @noErrors
import { createConfig, cookieStorage } from "@account-kit/react";
import { QueryClient } from "@tanstack/react-query";
import { sepolia } from "@account-kit/infra";
 
export const config = createConfig(
  {
    // alchemy config
    apiKey: "YOUR_API_KEY", // TODO: add your Alchemy API key - setup your app and embedded account config in the alchemy dashboard (https://dashboard.alchemy.com/accounts)
    chain: sepolia, // TODO: specify your preferred chain here and update imports from @account-kit/infra
    ssr: true, // Defers hydration of the account state to the client after the initial mount solving any inconsistencies between server and client state (read more here: https://accountkit.alchemy.com/react/ssr)
    storage: cookieStorage, // persist the account state using cookies (read more here: https://accountkit.alchemy.com/react/ssr#persisting-the-account-state)
  },
  {
    // authentication ui config - your customizations here
    auth: {
      sections: [
        [{ type: "email" }],
        [{ type: "passkey" }, { type: "external_wallets" }],
      ],
      addPasskeyOnSignup: true,
      showSignInText: true,
    },
  }
);
 
export const queryClient = new QueryClient();

4. Set up the Alchemy Provider

This example assumes you are using the NextJS app router.

However, the key pieces are applicable to any React app and you can structure the location of the code as needed.

4a. Create the provider - app/providers.tsx

Once you have styling and authentication configs, create a providers.tsx file and import the AlchemyAccountProvider.

The QueryClientProvider is also required to handle React Queries within the Alchemy Account Provider.

app/providers.tsx
"use client";
import { config, queryClient } from "@/config";
import { AlchemyClientState } from "@account-kit/core";
import { AlchemyAccountProvider } from "@account-kit/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { PropsWithChildren } from "react";
 
export const Providers = (
  props: PropsWithChildren<{ initialState?: AlchemyClientState }>
) => {
  return (
    <QueryClientProvider client={queryClient}>
      <AlchemyAccountProvider
        config={config}
        queryClient={queryClient}
        initialState={props.initialState}
      >
        {props.children}
      </AlchemyAccountProvider>
    </QueryClientProvider>
  );
};

4b. Use the provider - layout.tsx

Any component or page that will use Alchemy React components, must be wrapped by this Provider.

Additionally, we recommend using cookies to set the initial state when creating the provider to persist state across reloads (🧠 remember the cookie storage configured in step 3b).

For example, wrap your app with the created Provider by modifying your layout.tsx file.

app/layout.tsx
import { config } from "@/config";
import { cookieToInitialState } from "@account-kit/core";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { headers } from "next/headers";
import "./globals.css";
import { Providers } from "./providers";
 
const inter = Inter({ subsets: ["latin"] });
 
export const metadata: Metadata = {
  title: "Embedded Accounts UI Components Quickstart NextJs Template",
  description: "Embedded Accounts UI Components Quickstart NextJs Template",
};
 
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  // This will allow us to persist state across page boundaries (read more here: https://accountkit.alchemy.com/react/ssr#persisting-the-account-state)
  const initialState = cookieToInitialState(
    config,
    headers().get("cookie") ?? undefined
  );
 
  return (
    <html lang="en">
      <body className={inter.className}>
        <Providers initialState={initialState}>{children}</Providers>
      </body>
    </html>
  );
}

5. Run it

Once you have wrapped your app with the Alchemy Provider, you can now use the pre-built Alchemy react components for auth throughout your app.

All you need to do is useAuthModal! For example, pop open the auth modal like so:

app/page.tsx
"use client";
import {
  useAuthModal,
  useLogout,
  useSignerStatus,
  useUser,
} from "@account-kit/react";
 
export default function Home() {
  const user = useUser();
  const { openAuthModal } = useAuthModal();
  const signerStatus = useSignerStatus();
  const { logout } = useLogout();
 
  return (
    <main className="flex min-h-screen flex-col items-center p-24 gap-4 justify-center text-center">
      {signerStatus.isInitializing ? (
        <>Loading...</>
      ) : user ? (
        <div className="flex flex-col gap-2 p-2">
          <p className="text-xl font-bold">Success!</p>
          You're logged in as {user.email ?? "anon"}.<button
            className="btn btn-primary mt-6"
            onClick={() => logout()}
          >
            Log out
          </button>
        </div>
      ) : (
        <button className="btn btn-primary" onClick={openAuthModal}>
          Login
        </button>
      )}
    </main>
  );
}