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. By the end of this quickstart, you should have an AI application integrated with Auth0 that can:
  • Get an Auth0 access token.
  • Use the Auth0 access token to make a tool call to your API endpoint, in this case, Auth0’s /userinfo endpoint.
  • Return the data to the user via an AI agent.

Pick your tech stack

Prerequisites

Before getting started, make sure you have completed the following steps:
1

Create an Auth0 Account and a Dev Tenant

To continue with this quickstart, you need an Auth0 account and a Developer Tenant.
2

Create an Auth0 Application

Create and configure an Auth0 Application with the following properties:
  • Type: Regular Web
  • Allowed Callback URLs: http://localhost:3000/auth/callback
  • Allowed Logout URLs: http://localhost:3000
To learn more about Auth0 applications, read Applications.
3

OpenAI Platform

Prepare Next.js app

Recommended: To use a starter template, clone the Auth0 AI samples repository:
git clone https://github.com/auth0-samples/auth0-ai-samples.git
cd auth0-ai-samples/authenticate-users/langchain-next-js

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

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.

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;
    },
  });

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.",
  }
);

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 Vercel AI
OPENAI_API_KEY="YOUR_API_KEY"
If you use another provider for your LLM, adjust the variable name in .env.local accordingly.

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.Explore the example app on GitHub.

Next steps