> ## Documentation Index
> Fetch the complete documentation index at: https://docs.neynar.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 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](https://github.com/neynarxyz/farcaster-examples/tree/main/wownar-react-sdk) 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:

<CodeGroup>
  ```powershell Powershell theme={"system"}
  npx create-next-app app-name
  ```
</CodeGroup>

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

<Frame>
  <img src="https://mintcdn.com/neynar/4PNY113y9N9T-r9z/images/docs/c0af43f-image.png?fit=max&auto=format&n=4PNY113y9N9T-r9z&q=85&s=b9d898c07a54e7cef78e019a01984d78" width="1538" height="1238" data-path="images/docs/c0af43f-image.png" />
</Frame>

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

<CodeGroup>
  ```shell npm theme={"system"}
  npm i @neynar/react @neynar/nodejs-sdk axios
  ```

  ```shell yarn theme={"system"}
  yarn add @neynar/react @neynar/nodejs-sdk axios
  ```

  ```shell bun theme={"system"}
  bun add @neynar/react @neynar/nodejs-sdk axios
  ```
</CodeGroup>

Install peer dependencies for `@neynar/react`

<CodeGroup>
  ```shell npm theme={"system"}
  npm i @pigment-css/react@^0.0.30 hls.js@^1.5.20 react@^19.0.0 react-dom@^19.0.0 swr@^2.3.2
  ```

  ```shell yarn theme={"system"}
  yarn add @pigment-css/react@^0.0.30 hls.js@^1.5.20 react@^19.0.0 react-dom@^19.0.0 swr@^2.3.2
  ```

  ```shell bun theme={"system"}
  bun add @pigment-css/react@^0.0.30 hls.js@^1.5.20 react@^19.0.0 react-dom@^19.0.0 swr@^2.3.2
  ```
</CodeGroup>

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:

<CodeGroup>
  ```typescript layout.tsx theme={"system"}
  "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>
    );
  }
  ```
</CodeGroup>

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`.

<Frame>
  <img src="https://mintcdn.com/neynar/4PNY113y9N9T-r9z/images/docs/bde5490-image.png?fit=max&auto=format&n=4PNY113y9N9T-r9z&q=85&s=c44bb9404a8361f45b82f97d08e9feb8" width="1522" height="1872" data-path="images/docs/bde5490-image.png" />
</Frame>

<Info>
  ### Make sure to add localhost to the authorized origins
</Info>

* `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:

<CodeGroup>
  ```typescript page.tsx theme={"system"}
  "use client";

  import { NeynarAuthButton } 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>
    );
  }
  ```
</CodeGroup>

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!

<Frame>
  <img src="https://mintcdn.com/neynar/aGwjtKmNewHJXSzO/images/docs/4813dc2-image.png?fit=max&auto=format&n=aGwjtKmNewHJXSzO&q=85&s=2aefa20261f34feab92e7275ff564047" width="396" height="196" data-path="images/docs/4813dc2-image.png" />
</Frame>

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:

<CodeGroup>
  ```typescript page.tsx theme={"system"}
    const { user } = useNeynarContext();
  ```
</CodeGroup>

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:

<CodeGroup>
  ```typescript page.tsx theme={"system"}
  "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" style={{fontWeight: 500}}>{user?.display_name}</p>
              </div>
            </div>
          </>
        )}
      </main>
    );
  }
  ```
</CodeGroup>

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

<CodeGroup>
  ```typescript page.tsx theme={"system"}
  {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" style={{fontWeight: 500}}>{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>
      </>
    );
  }
  ```
</CodeGroup>

This will give you something like this:

<Frame>
  <img src="https://mintcdn.com/neynar/4PNY113y9N9T-r9z/images/docs/88935ab-image.png?fit=max&auto=format&n=4PNY113y9N9T-r9z&q=85&s=28074bef83f6ba45d63c28891a20e8b5" width="1350" height="902" data-path="images/docs/88935ab-image.png" />
</Frame>

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:

<CodeGroup>
  ```typescript page.tsx theme={"system"}
    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);
      }
    };
  ```
</CodeGroup>

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:

<CodeGroup>
  ```typescript cast/route.ts theme={"system"}
  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 }
        );
    }
  }
  ```
</CodeGroup>

<Info>
  ### Make sure to set the NEYNAR\_API\_KEY variable in your .env.local file
</Info>

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](https://github.com/neynarxyz/farcaster-examples/tree/main/wownar-react-sdk) if you want to look at the full code.

Lastly, make sure to share what you built with us on Farcaster by tagging [@neynar](https://warpcast.com/neynar) and if you have any questions, reach out to us on [warpcast](https://warpcast.com/~/channel/neynar) or [Slack](https://neynar.com/slack)!
