Skip to main content
Use Auth0 SDKs to fetch access tokens for social and enterprise identity providers from Auth0’s Token Vault. Using these access tokens, AI agents integrated with the application can call third-party APIs to perform tasks on the user’s behalf.

What you’ll learn

  • Retrieve access tokens for a Google social connection.
  • Integrate with an AI agent to call Google APIs.
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

OpenAI Platform

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

Getting started using AI

To get started quickly:
Clone auth0-samples/auth0-ai-samples and navigate to auth0-ai-samples/call-apis-on-users-behalf/others-api/vercel-ai-next-js 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

Install packages

In the root directory of your project, install the following packages:
  • @auth0/ai-vercel: Auth0 AI SDK for AI SDK built for AI agents powered by the AI SDK.
  • ai: Core AI SDK module that interacts with various AI model providers.
  • @ai-sdk/openai: OpenAI provider for the AI SDK.
  • @ai-sdk/react: React UI components for the AI SDK.
  • zod: TypeScript-first schema validation library.
  • googleapis: Node.js client for Google APIs that supports authentication and authorization with OAuth 2.0.
npm install @auth0/ai-vercel@4 ai@5.0.33 @ai-sdk/openai@2.0.24 @ai-sdk/react@2.0.33 zod@3.25.76 googleapis@161
2

Update your environment file

Add the following variables to your environment file:
.env.local
# Auth0 configuration
APP_BASE_URL='http://localhost:3000'
AUTH0_SECRET='random 32 byte value'
AUTH0_DOMAIN='<your-auth0-domain>'
AUTH0_CLIENT_ID='<your-auth0-application-client-id>'
AUTH0_CLIENT_SECRET='<your-auth0-application-client-secret>'

# OpenAI API Key or any provider supported by the AI SDK
OPENAI_API_KEY="YOUR_API_KEY"

# LANGGRAPH
LANGGRAPH_API_URL=http://localhost:54367
LANGCHAIN_CALLBACKS_BACKGROUND=false
To get your Auth0 application’s AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET, navigate to the Settings tab in the Auth0 Dashboard. You’ll find these values in the Basic Information section at the top. Copy each value to the matching setting.Next, run this command to generate a random 32 byte value and copy it to the AUTH0_SECRET field:
generate random 32 byte value
openssl rand -hex 32
Lastly, set your OpenAI API key or use any provider supported by the AI SDK:
3

Set up Token Vault

Use the Auth0 AI SDK for AI SDK to get an access token for the Google Social Connection using Token Vault:
  • connection: pass in the name of the connection you want to access.
  • scopes: pass in the scopes to be authorized for this connection.
  • refreshToken: pass in the function to get the refresh token from the current session.
Create a file at src/lib/auth0-ai.ts to instantiate the Auth0 AI SDK client:
src/lib/auth0-ai.ts
import { Auth0AI, getAccessTokenFromTokenVault } from "@auth0/ai-vercel";
import { getRefreshToken } from "./auth0";

// Get the access token for a connection via Auth0
export const getAccessToken = async () => getAccessTokenFromTokenVault();

const auth0AI = new Auth0AI();

// Connection for Google services
export const withGoogleConnection = auth0AI.withTokenVault({
  connection: "google-oauth2",
  scopes: ["https://www.googleapis.com/auth/calendar.events"],
  refreshToken: getRefreshToken,
});
4

Pass credentials to the tools

Create a file at /src/lib/auth0.ts file with the following code:
src/lib/auth0.ts
import { Auth0Client } from '@auth0/nextjs-auth0/server';

// Create an Auth0 Client.
export const auth0 = new Auth0Client();

// Get the refresh token from Auth0 session
export const getRefreshToken = async () => {
  const session = await auth0.getSession();
  return session?.tokenSet?.refreshToken;
};

Use access token to call APIs from a tool

Once the user is authenticated, you can fetch an access token from the Token Vault using the Auth0 AI SDK. In this example, we fetch an access token for a Google social connection. Once you’ve obtained the access token for a social connection, you can use it with an AI agent to fetch data during a tool call and provide contextual data in its response.In this example, we define a tool call, getCalendarEventsTool, that uses the access token with the Google Calendar API to query for calendar events on a specific date. Update your tool call to request an access token similar to this example:
src/lib/tools/google-calendar.ts
import { tool } from 'ai';
import { endOfDay, formatISO, startOfDay } from 'date-fns';
import { GaxiosError } from 'gaxios';
import { google } from 'googleapis';
import { z } from 'zod';
import { TokenVaultError } from '@auth0/ai/interrupts';

import { getAccessToken, withGoogleConnection } from '../auth0-ai';

export const getCalendarEventsTool = withGoogleConnection(
  tool({
    description: `Get calendar events for a given date from the user's Google Calendar`,
    inputSchema: z.object({
      date: z.coerce.date(),
    }),
    execute: async ({ date }) => {
      // Get the access token from Auth0 AI
      const accessToken = await getAccessToken();

      // Google SDK
      try {
        const calendar = google.calendar('v3');
        const auth = new google.auth.OAuth2();

        auth.setCredentials({
          access_token: accessToken,
        });

        // Get events for the entire day
        const response = await calendar.events.list({
          auth,
          calendarId: 'primary',
          timeMin: formatISO(startOfDay(date)),
          timeMax: formatISO(endOfDay(date)),
          singleEvents: true,
          orderBy: 'startTime',
          maxResults: 50,
        });

        const events = response.data.items || [];

        return {
          date: formatISO(date, { representation: 'date' }),
          eventsCount: events.length,
          events: events.map((event) => ({
            id: event.id,
            summary: event.summary || 'No title',
            description: event.description,
            startTime: event.start?.dateTime || event.start?.date,
            endTime: event.end?.dateTime || event.end?.date,
            location: event.location,
            attendees:
              event.attendees?.map((attendee) => ({
                email: attendee.email,
                name: attendee.displayName,
                responseStatus: attendee.responseStatus,
              })) || [],
            status: event.status,
            htmlLink: event.htmlLink,
          })),
        };
      } catch (error) {
        if (error instanceof GaxiosError) {
          if (error.status === 401) {
            throw new TokenVaultError(`Authorization required to access the Token Vault connection`);
          }
        }

        throw error;
      }
    },
  }),
);
5

Add step up authorization

When you try to use the tool, the application requests any additional Google scopes that are required but not yet authorized. This process is called step-up authorization.To implement, install the Auth0 AI Components for Next.js SDK to get the required UI components:
npx @auth0/ai-components add TokenVault
Add a new file, src/components/auth0-ai/TokenVault/TokenVaultInterruptHandler.tsx with the following code:
src/components/auth0-ai/TokenVault/TokenVaultInterruptHandler.tsx
import { TokenVaultInterrupt } from "@auth0/ai/interrupts";
import type { Auth0InterruptionUI } from "@auth0/ai-vercel/react";

import { TokenVaultConsent } from "@/components/auth0-ai/TokenVault";

interface TokenVaultInterruptHandlerProps {
  interrupt: Auth0InterruptionUI | null;
}

export function TokenVaultInterruptHandler({
  interrupt,
}: TokenVaultInterruptHandlerProps) {
  if (!TokenVaultInterrupt.isInterrupt(interrupt)) {
    return null;
  }

  return (
    <div key={interrupt.name} className="whitespace-pre-wrap">
      <TokenVaultConsent
        mode="popup"
        interrupt={interrupt}
        connectWidget={{
          title: "Authorization Required.",
          description: interrupt.message,
          action: { label: "Authorize" },
        }}
      />
    </div>
  );
}
Now, update your chat window code to include the TokenVaultInterruptHandler component, for example:
src/components/chat-window.tsx
//...
import { useInterruptions } from '@auth0/ai-vercel/react';
import { TokenVaultInterruptHandler } from '@/components/auth0-ai/TokenVault/TokenVaultInterruptHandler';


//... existing code
export function ChatWindow(props: {
  //... existing code
}) {
  const chat = useInterruptions((handler) =>
    useChat({
      api: props.endpoint,
      onError: handler((e: Error) => {
        console.error('Error: ', e);
        toast.error(`Error while processing your request`, { description: e.message });
      }),
    }),
  );

  //... existing code
  return (
    <StickToBottom>
      <StickyToBottomContent
        className="absolute inset-0"
        contentClassName="py-8 px-2"
        content={
          chat.messages.length === 0 ? (
            <div>{props.emptyStateComponent}</div>
          ) : (
            <>
              <ChatMessages
                aiEmoji={props.emoji}
                messages={chat.messages}
                emptyStateComponent={props.emptyStateComponent}
              />
              <div className="flex flex-col max-w-[768px] mx-auto pb-12 w-full">
                <TokenVaultInterruptHandler interrupt={chat.toolInterrupt} />
              </div>
            </>
          )
        }
        {/* ... existing code */}
      ></StickyToBottomContent>
    </StickToBottom>
  );
}
Now when step-up authorization is required, the user will see a prompt in the chat window asking them to authorize.
6

Add the tool to the AI agent

Handle the interrupts from the AI agent and call the tool from your AI app to get calendar events. Update your chat route, typically at /src/app/api/chat/route.ts, as shown in the following example:
src/app/api/chat/route.ts
//...
import { setAIContext } from "@auth0/ai-vercel";
import {
  errorSerializer,
  withInterruptions,
} from "@auth0/ai-vercel/interrupts";
import { getCalendarEventsTool } from "@/lib/tools/google-calendar";
//... existing code

export async function POST(req: NextRequest) {
  const request = await req.json();
  const messages = sanitizeMessages(request.messages);

  setAIContext({ threadID: request.id });

  const tools = {
    getCalendarEventsTool,
  };

   const modelMessages = convertToModelMessages(messages);

  const stream = createUIMessageStream({
    originalMessages: messages,
    execute: withInterruptions(
      async ({ writer }) => {
        const result = streamText({
          model: openai('gpt-4o-mini'),
          system: AGENT_SYSTEM_TEMPLATE,
          messages: modelMessages,
          tools,

          onFinish: (output) => {
            if (output.finishReason === 'tool-calls') {
              const lastMessage = output.content[output.content.length - 1];
              if (lastMessage?.type === 'tool-error') {
                const { toolName, toolCallId, error, input } = lastMessage;
                const serializableError = {
                  cause: error,
                  toolCallId: toolCallId,
                  toolName: toolName,
                  toolArgs: input,
                };

                throw serializableError;
              }
            }
          },
        });
        writer.merge(
          result.toUIMessageStream({
            sendReasoning: true,
          }),
        );
      },
      {
        messages: messages,
        tools,
      },
    ),
    onError: errorSerializer((err) => {
      console.error('ai-sdk route: stream error', err);
      return 'Oops, an error occured!';
    }),
  });

  return createUIMessageStreamResponse({ stream });
}
7

Test your application

Start your application. If you are already logged in, make sure to log out and log back in using Google. Then, ask your AI agent about your Google calendar!That’s it! You successfully integrated third-party API access using Token Vault into your app.

Continue Learning

How-Tos