Skip to main content
Let your AI agent call your APIs on behalf of the authenticated user using access tokens securely issued by Auth0. Your API can be any API that you have configured in Auth0.

What you’ll learn

  • Obtain an access token: learn how to authenticate and securely retrieve an access token from Auth0.
  • Call an API: use the token to make a request to your API (e.g.: Auth0’s /userinfo endpoint).
  • Present user data: pass the retrieved data back through an AI agent for consumption or display.
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/fastapi-light.svg FastAPI

Getting started using AI

To get started quickly:
Clone auth0-samples/auth0-ai-samples and navigate to call-apis-on-users-behalf/your-api/langchain-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 dependencies

In the root directory of your project, install the following dependencies:
  • @langchain/langgraph: The core LangGraph module.
  • @langchain/openai: OpenAI provider for LangChain.
  • langchain: The core LangChain module.
  • zod: TypeScript-first schema validation library.
  • langgraph-nextjs-api-passthrough: API passthrough for LangGraph.
npm install @langchain/langgraph@0.3 @langchain/openai@0.6 langchain@0.3 zod@3 langgraph-nextjs-api-passthrough@0.1
2

Update the environment file

Copy the .env.example file to .env.local and update the variables with your Auth0 credentials. You can find your Auth0 domain, client ID, and client secret in the application you created in the Auth0 Dashboard.
3

Pass credentials to the agent

You have to pass the access token from the user’s session to the agent. First, create a helper function to get the access token from the session. Add the following function to src/lib/auth0.ts:
src/lib/auth0.ts
//...

// Get the Access token from Auth0 session
export const getAccessToken = async () => {
  const session = await auth0.getSession();
  return session?.tokenSet?.accessToken;
};
Now, update the /src/app/api/chat/[..._path]/route.ts file to pass the access token to the agent:
src/app/api/chat/[..._path]/route.ts
import { initApiPassthrough } from "langgraph-nextjs-api-passthrough";

import { getAccessToken } from "@/lib/auth0";

export const { GET, POST, PUT, PATCH, DELETE, OPTIONS, runtime } =
  initApiPassthrough({
    apiUrl: process.env.LANGGRAPH_API_URL,
    baseRoute: "chat/",
    bodyParameters: async (req, body) => {
      if (
        req.nextUrl.pathname.endsWith("/runs/stream") &&
        req.method === "POST"
      ) {
        return {
          ...body,
          config: {
            configurable: {
              _credentials: {
                accessToken: await getAccessToken(),
              },
            },
          },
        };
      }

      return body;
    },
  });
4

Define a tool to call your API

In this step, you’ll create a LangChain tool to make the first-party API call. The tool fetches an access token to call the API.In this example, after taking in an Auth0 access token during user login, the tool returns the user profile of the currently logged-in user by calling the /userinfo endpoint.
src/lib/tools/user-info.ts
import { tool } from "@langchain/core/tools";

export const getUserInfoTool = tool(
  async (_input, config?) => {
    // Access credentials from config
    const accessToken = config?.configurable?._credentials?.accessToken;
    if (!accessToken) {
      return "There is no user logged in.";
    }

    const response = await fetch(
      `https://${process.env.AUTH0_DOMAIN}/userinfo`,
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    );

    if (response.ok) {
      return { result: await response.json() };
    }

    return "I couldn't verify your identity";
  },
  {
    name: "get_user_info",
    description: "Get information about the current logged in user.",
  }
);
5

Add the tool to the AI agent

The AI agent processes and runs the user’s request through the AI pipeline, including the tool call. Update the /src/lib/agent.ts file to add the tool to the agent.
src/lib/agent.ts
//...
import { getUserInfoTool } from "./tools/user-info";

//... existing code

const tools = [
  //... existing tools
  getUserInfoTool,
];

//... existing code
You need an API Key from OpenAI or another provider to use an LLM. Add that API key to your .env.local file:
.env.local
# ...
# You can use any provider of your choice supported by AI SDK
OPENAI_API_KEY="YOUR_API_KEY"
If you use another provider for your LLM, adjust the variable name in .env.local accordingly.
6

Test your application

To test the application, run npm run all:dev and navigate to http://localhost:3000.
This will open the LangGraph Studio in a new tab. You can close it as we won’t require it for testing the application.
To interact with the AI agent, you can ask questions like "who am I?" to trigger the tool call and test whether it successfully retrieves information about the logged-in user.
User: who am I?
AI: It seems that there is no user currently logged in. If you need assistance with anything else, feel free to ask!

User: who am I?
AI: You are Deepu Sasidharan. Here are your details: - .........
That’s it! You’ve successfully integrated first-party tool-calling into your project.

Continue Learning

How-Tos