Skip to main content

What you’ll learn

  • Authenticate with Auth0 AI: configure Auth0 AI and obtain federated access tokens for GitHub APIs.
  • Call external APIs securely: use the token to list repositories through a AI SDK tool.
  • Handle auth interruptions: enable dynamic user consent and reauthorization within chat flows.
Before getting started, make sure you have completed the following steps:
1

Create an Auth0 Account

To continue with this quickstart, you need to have an Auth0 account.
2

Create an Auth0 Application

Go to your Auth0 Dashboard to create a new Auth0 Application.
  • Navigate to Applications > Applications in the left sidebar.
  • Click the Create Application button in the top right.
  • In the pop-up select Regular Web Applications and click Create.
  • Once the Application is created, switch to the Settings tab.
  • Scroll down to the Application URIs section.
  • Set Allowed Callback URLs as: http://localhost:3000/auth/callback
  • Set Allowed Logout URLs as: http://localhost:3000
  • Click Save in the bottom right to save your changes.
3

Configure Google Social Integration

Set up a Google developer account that allows for third-party API calls by following the Google Social Integration instructions.
4

OpenAI Platform

  • https://mintlify.s3.us-west-1.amazonaws.com/auth0-genai-feat-add-diagrams-modal-with-steps/img/nextjs-light.svg Next.js

Getting started using AI

To get started quickly:
Clone auth0-lab/auth0-ai-js and navigate to examples/calling-apis/chatbot/app/(ai-sdk) directory.
Then, integrate Auth0 AI docs into your preferred AI tool:

  • VS Code
  • Cursor
  • Claude Code
  • Claude
Create a .vscode/mcp.json file and add:
{
  "servers": {
    "Auth0 for AI Agents": {
      "type": "http",
      "url": "https://auth0.com/ai/docs/mcp"
    }
  }
}
To learn more, read the VS Code documentation.

or Follow manual steps

1

Configure Auth0 AI

First, you must install the SDK:
npm install @auth0/ai-vercel
Then, you need to initialize Auth0 AI and set up the connection to request access tokens with the required GitHub scopes.
./src/lib/auth0-ai.ts
import { Auth0AI } from "@auth0/ai-vercel";
import { auth0 } from "@/lib/auth0";

const auth0AI = new Auth0AI();

export const withGitHub = auth0AI.withTokenVault({
  connection: "github",
  scopes: ["repo"],
  refreshToken: async () => {
    const session = await auth0.getSession();
    const refreshToken = session?.tokenSet.refreshToken as string;

    return refreshToken;
  },
});
Here, the property auth0 is an instance of @auth0/nextjs-auth0 to handle the application auth flows.
You can check different authentication options for Next.js with Auth0 at the official documentation.
2

Integrate your tool with GitHub

Wrap your tool using the Auth0 AI SDK to obtain an access token for the GitHub API.
./src/lib/tools/listRepositories.ts
import { Octokit, RequestError } from "octokit";
import { getAccessTokenFromTokenVault } from "@auth0/ai-vercel";
import { TokenVaultError } from "@auth0/ai/interrupts";
import { withGitHub } from "@/lib/auth0-ai";
import { tool } from "ai";
import { z } from "zod";


export const listRepositories = withGitHub(
  tool({
    description: "List respositories for the current user on GitHub",
    parameters: z.object({}),
    execute: async () => {
      // Get the access token from Auth0 AI
      const accessToken = getAccessTokenFromTokenVault();

      // GitHub SDK
      try {
        const octokit = new Octokit({
          auth: accessToken,
        });

        const { data } = await octokit.rest.repos.listForAuthenticatedUser();

        return data.map((repo) => repo.name);
      } catch (error) {
        console.log("Error", error);

        if (error instanceof RequestError) {
          if (error.status === 401) {
            throw new TokenVaultError(
              `Authorization required to access the Token Vault connection`
            );
          }
        }

        throw error;
      }
    },
  })
);
3

Handle authentication redirects

Interrupts are a way for the system to pause execution and prompt the user to take an action—such as authenticating or granting API access—before resuming the interaction. This ensures that any required access is granted dynamically and securely during the chat experience. In this context, Auth0-AI SDK manages authentication redirects in the AI SDK via these interrupts.

Server Side

On the server-side code of your Next.js App, you need to set up the tool invocation and handle the interruption messaging via the errorSerializer. The setAIContext function is used to set the async-context for the Auth0 AI SDK.
./src/app/api/chat/route.ts
import { createDataStreamResponse, Message, streamText } from "ai";
import { listRepositories } from "@/lib/tools/";
import { setAIContext } from "@auth0/ai-vercel";
import { errorSerializer, withInterruptions } from "@auth0/ai-vercel/interrupts";
import { openai } from "@ai-sdk/openai";

export async function POST(request: Request) {
  const { id, messages} = await request.json();
  const tools = { listRepositories };
  setAIContext({ threadID: id });

  return createDataStreamResponse({
    execute: withInterruptions(
      async (dataStream) => {
        const result = streamText({
          model: openai("gpt-4o-mini"),
          system: "You are a friendly assistant! Keep your responses concise and helpful.",
          messages,
          maxSteps: 5,
          tools,
        });

        result.mergeIntoDataStream(dataStream, {
          sendReasoning: true,
        });
      },
      { messages, tools }
    ),
    onError: errorSerializer((err) => {
      console.log(err);
      return "Oops, an error occured!";
    }),
  });
}

Client Side

On this example we utilize the TokenVaultConsentPopup component to show a popup that allows the user to authenticate with GitHub and grant access with the requested scopes. You’ll first need to install the @auth0/ai-components package:
npx @auth0/ai-components add TokenVault
Then, you can integrate the authentication popup in your chat component, using the interruptions helper from the SDK:
./src/components/chat.tsx
"use client";

import { useChat } from "@ai-sdk/react";
import { useInterruptions } from "@auth0/ai-vercel/react";
import { TokenVaultInterrupt } from "@auth0/ai/interrupts";
import { TokenVaultConsentPopup } from "@/components/auth0-ai/TokenVault/popup";

export default function Chat() {
  const { messages, handleSubmit, input, setInput, toolInterrupt } =
    useInterruptions((handler) =>
      useChat({
        onError: handler((error) => console.error("Chat error:", error)),
      })
    );

  return (
    <div>
      {messages.map((message) => (
        <div key={message.id}>
          {message.role === "user" ? "User: " : "AI: "}
          {message.content}
        </div>
      ))}

      {TokenVaultInterrupt.isInterrupt(toolInterrupt) && (
        <TokenVaultConsentPopup
          interrupt={toolInterrupt}
          connectWidget={{
            title: "List GitHub respositories",
            description:"description ...",
            action: { label: "Check" },
          }}
        />
      )}

      <form onSubmit={handleSubmit}>
        <input value={input} placeholder="Say something..." onChange={(e) => setInput(e.target.value)} />
      </form>
    </div>
  );
}

Account Linking

If you're integrating with GitHub, but users in your app or agent can sign in using other methods (e.g., a username and password or another social provider), you'll need to link these identities into a single user account. Auth0 refers to this process as Account Linking.Account Linking logic and handling will vary depending on your app or agent. You can find an example of how to implement it in a Next.js chatbot app here. If you have questions or are looking for best practices, join our Discord and ask in the #auth0-for-gen-ai channel.

How-Tos