SIWN: React

In this guide, we'll take a look at how to implement sign-in with neynar in a React app. For this guide, I am going to be using next.js but the same would work for CRA, remix, or anything based on react!

For this guide, we'll go over:

  1. Setting up auth using the Neynar React SDK
  2. Using the signer to create casts

Before we begin, you can access the complete source code for this guide on GitHub.

Let's get started!

Creating the app

Setting up the project

Create a new next.js app using the following command:

npx create-next-app app-name

You can choose the configuration based on your personal preference, I am using this config for the guide:

Once the app is created, install the packages that we are going to need for the command:

npm i @neynar/react @neynar/nodejs-sdk axios 
yarn add @neynar/react @neynar/nodejs-sdk axios 
bun add @neynar/react @neynar/nodejs-sdk axios 

Once the dependencies are installed you can open it in your favourite and we can start working on adding sign-in with neynar!

Adding the sign-in button

Head over to the layout.tsx file and wrap your app in a NeynarContextProvider like this:

"use client";

import { NeynarContextProvider, Theme } from "@neynar/react";
import "@neynar/react/dist/style.css";
import { Inter } from "next/font/google";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <NeynarContextProvider
        settings={{
          clientId: process.env.NEXT_PUBLIC_NEYNAR_CLIENT_ID || "",
          defaultTheme: Theme.Light,
          eventsCallbacks: {
            onAuthSuccess: () => {},
            onSignout() {},
          },
        }}
      >
        <body className={inter.className}>{children}</body>
      </NeynarContextProvider>
    </html>
  );
}

We are passing some settings here like clientId, defaultTheme and eventsCallbacks.

  • clientId: This is going to be the client ID you get from your neynar, add it to your .env.local file as NEXT_PUBLIC_NEYNAR_CLIENT_ID.

📘

Make sure to add localhost to the authorized origins

  • defaultTheme: default theme lets you change the theme of your sign-in button, currently, we have only light mode but dark mode is going to be live soon.
  • eventsCallbacks: This allows you to perform certain actions when the user signs out or auth is successful.

I've also added a styles import from the neynar react package here which is needed for the styles of the sign-in button.

Finally, let's add the sign-in button in the page.tsx file like this:

"use client";

import { NeynarAuthButton, useNeynarContext } from "@neynar/react";

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div className="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex">
        <NeynarAuthButton />
      </div>
    </main>
  );
}

If you head over to your app you'll be able to see a sign-in button on the screen. Go ahead and try signing in!

Now that our sign-in button is working let's use the signer we get to publish casts!

Using the signer UUID to publish casts

In the page.tsx file access the user data using the useNeynarContext hook like this:

  const { user } = useNeynarContext();

The user object contains various information like the username, fid, display name, pfp url, signer uuid, etc.

Then, we can use this user object to check whether the user has signed in and display a screen conditionally like this:

"use client";

import { NeynarAuthButton, useNeynarContext } from "@neynar/react";
import Image from "next/image";

export default function Home() {
  const { user } = useNeynarContext();

  return (
    <main className="flex min-h-screen flex-col items-center p-24">
      <NeynarAuthButton />

      {user && (
        <>
          <div className="flex flex-col gap-4 w-96 p-4 rounded-md shadow-md">
            <div className="flex items-center gap-4">
              {user.pfp_url && (
                <Image
                  src={user.pfp_url}
                  width={40}
                  height={40}
                  alt="User Profile Picture"
                  className="rounded-full"
                />
              )}
              <p className="text-lg font-semibold">{user?.display_name}</p>
            </div>
          </div>
        </>
      )}
    </main>
  );
}

Now, let's add a text area and a cast button here like this:

{user && (
    <>
      <div className="flex flex-col gap-4 w-96 p-4 rounded-md shadow-md">
        <div className="flex items-center gap-4">
          {user.pfp_url && (
            <Image
              src={user.pfp_url}
              width={40}
              height={40}
              alt="User Profile Picture"
              className="rounded-full"
            />
          )}
          <p className="text-lg font-semibold">{user?.display_name}</p>
        </div>
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Say Something"
          rows={5}
          className="w-full p-2 rounded-md shadow-md text-black placeholder:text-gray-900"
        />
      </div>
      <button
        onClick={handlePublishCast}
        className="mt-4 px-4 py-2 bg-blue-500 text-white rounded-md shadow-md hover:bg-blue-600 transition-colors duration-200 ease-in-out"
      >
        Cast
      </button>
    </>
  );
}

This will give you something like this:

But as you can see we have used a handlePublishCast function but we have not yet created it. So, let's create that and also add the text useState that we are using in the textarea:

  const [text, setText] = useState("");

  const handlePublishCast = async () => {
    try {
      await axios.post<{ message: string }>("/api/cast", {
        signerUuid: user?.signer_uuid,
        text,
      });
      alert("Cast Published!");
      setText("");
    } catch (err) {
      const { message } = (err as AxiosError).response?.data as ErrorRes;
      alert(message);
    }
  };

This creates an api call to a /api/cast route with the signer uuid and text.

Finally, we need to create the api route which will create casts. Create a new file api/cast/route.ts in the app folder and add the following:

import { NextRequest, NextResponse } from "next/server";
import { NeynarAPIClient, isApiErrorResponse } from "@neynar/nodejs-sdk";

const client = new NeynarAPIClient(process.env.NEYNAR_API_KEY!);

export async function POST(request: NextRequest) {
  const { signerUuid, text } = (await request.json()) as {
    signerUuid: string;
    text: string;
  };

  try {
    const { hash } = await client.publishCast(signerUuid, text);
    return NextResponse.json(
      { message: `Cast with hash ${hash} published successfully` },
      { status: 200 }
    );
  } catch (err) {
    if (isApiErrorResponse(err)) {
      return NextResponse.json(
        { ...err.response.data },
        { status: err.response.status }
      );
    } else
      return NextResponse.json(
        { message: "Something went wrong" },
        { status: 500 }
      );
  }
}

📘

Make sure to set the NEYNAR_API_KEY variable in your .env.local file

Now, you can go ahead and try making a cast from the website after connecting your Farcaster account! 🥳

Conclusion

This guide taught us how to add sign-in with neynar to a React app, check out the GitHub repository if you want to look at the full code.

Lastly, make sure to share what you built with us on Farcaster by tagging @neynar and if you have any questions, reach out to us on warpcast or Telegram!