Skip to main content

Auth0 SDKs

Updated SDKs now include enhanced support for securing AI agent workflows, including improved token management, API protection, and identity integration for AI-powered apps.

Next.js

This SDK streamlines integrating Auth0 authentication and authorization services into Next.js applications. It supports:
  • User authentication
  • Tools for getting access tokens for supported social and enterprise identity providers
npm install @auth0/nextjs-auth0
Below are code samples demonstrating how to integrate nextjs-auth0 in AI-related use cases. Each example highlights common patterns for building secure and scalable generative AI applications. For additional examples, click here.
You can retrieve an access token for a connection using the getAccessTokenForConnection() method, which accepts an object with the following properties:
  • connection: The federated connection for which an access token should be retrieved.
  • login_hint: The optional login_hint parameter to pass to the /authorize endpoint.
// Adjust path if your auth0 client is elsewhere
import { auth0 } from "./lib/auth0";
import { NextResponse } from "next/server";

export async function GET() {
  try {
    const token = await auth0.getAccessTokenForConnection({
      connection: "google-oauth2"
    });
    // call external API with token...
  } catch (err) {
    // err will be an instance of AccessTokenError
    // if an access token could not be obtained
  }

  return NextResponse.json({
    message: "Success!"
  });
}
In the browser
To access the currently authenticated user on the client, you can use the useUser() hook, like so:
"use client";

import { useUser } from "@auth0/nextjs-auth0";

export default function Profile() {
  const { user, isLoading, error } = useUser();

  if (isLoading) return <div>Loading...</div>;

  return (
    <main>
      <h1>Profile</h1>
      <div>
        <pre>{JSON.stringify(user, null, 2)}</pre>
      </div>
    </main>
  );
}
On the server (App Router)
On the server, the getSession() helper can be used in Server Components, Server Routes, and Server Actions to get the session of the currently authenticated user and to protect resources, like so:
import { auth0 } from "@/lib/auth0";

export default async function Home() {
  const session = await auth0.getSession();

  if (!session) {
    return <div>Not authenticated</div>;
  }

  return (
    <main>
      <h1>Welcome, {session.user.name}!</h1>
    </main>
  );
}
Requests to /api/protected without a valid session cookie will fail with 401.
app/api/protected/route.js
import { auth0 } from "@/lib/auth0";

export const GET = auth0.withApiAuthRequired(async function myApiRoute(req) {
  const res = new NextResponse();
  const { user } = await auth0.getSession(req);
  return NextResponse.json({ protected: "My Secret", id: user.sub }, res);
});
Then you can access your API from the frontend with a valid session cookie.
app/products/page.jsx
"use client";

import { withPageAuthRequired } from "@auth0/nextjs-auth0";
import useSWR from "swr";

const fetcher = async (uri) => {
  const response = await fetch(uri);
  return response.json();
};

export default withPageAuthRequired(function Products() {
  const { data, error } = useSWR("/api/protected", fetcher);
  if (error) return <div>oops... {error.message}</div>;
  if (data === undefined) return <div>Loading...</div>;
  return <div>{data.protected}</div>;
});
Using Client-Initiated Backchannel Authentication can be done by calling getTokenByBackchannelAuth():
  • bindingMessage: A human-readable message to be displayed at the consumption device and authentication device. This allows the user to ensure the transaction initiated by the consumption device is the same that triggers the action on the authentication device.
  • loginHint.sub: The sub claim of the user that is trying to login using Client-Initiated Backchannel Authentication, and to which a push notification to authorize the login will be sent.
import { auth0 } from "@/lib/auth0";

const tokenResponse = await auth0.getTokenByBackchannelAuth({
  bindingMessage: "",
  loginHint: {
    sub: "auth0|123456789"
  }
});

Node SDK

This library streamlines integrating Auth0’s authentication and authorization services into Node.js applications. It supports:
  • User authentication
  • Tools for signing up users, managing user profiles, and securing API endpoints.
npm install auth0

Fastify SDK

This SDK streamlines integrating Auth0 authentication and authorization services into Fastify applications. It supports:
  • User authentication
  • Tools for getting access tokens to call first-party APIs
npm i @auth0/auth0-fastify
Below are code samples demonstrating how to integrate Fastify + Auth0 in web applications. Each example highlights common patterns for handling user sessions, protecting routes, and rendering authenticated views. For more examples, click here.
This example shows how to protect API routes using Auth0 in a Fastify server. You can secure endpoints by requiring authentication or specific scopes using the @auth0/auth0-fastify-api plugin. Public routes stay open to everyone, while private ones require a valid access token.
import Fastify, { FastifyRequest } from 'fastify';
import fastifyAuth0Api from '@auth0/auth0-fastify-api';
import 'dotenv/config';

const fastify = Fastify();

fastify.register(fastifyAuth0Api, {
  domain: process.env.AUTH0_DOMAIN as string,
  audience: process.env.AUTH0_AUDIENCE as string,
});

fastify.register(() => {
  fastify.get(
    '/api/private',
    { preHandler: fastify.requireAuth() },
    async (request: FastifyRequest) => {
      return `Hello, ${request.user.sub}`;
    }
  );
});

fastify.register(() => {
  fastify.get(
    '/api/private-scope',
    { preHandler: fastify.requireAuth({ scopes: ['read:private'] }) },
    async (request: FastifyRequest) => {
      return `Hello, ${request.user.sub}`;
    }
  );
});

fastify.register(() => {
  fastify.get('/api/public', async () => {
    return `Hello world!`;
  });
});

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
  } catch (err) {
    process.exit(1);
  }
};

start();
This example shows how to integrate Auth0 into a Fastify web app:
  • You register @auth0/auth0-fastify with your domain, client credentials, base URL, and session secret.
  • Use fastify.auth0Client.getUser(...) to check if a user is logged in and fetch their profile.
  • To protect a route (like /private), you use a preHandler that checks for a valid session and redirects to Auth0’s login page if needed.
  • Auth0 handles the login, callback, and logout flows internally via the plugin’s built-in routes.
import Fastify, { FastifyReply, FastifyRequest } from 'fastify';
import fastifyStatic from '@fastify/static';
import fastifyView from '@fastify/view';
import fastifyAuth0 from '@auth0/auth0-fastify';
import ejs from 'ejs';
import 'dotenv/config';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const fastify = Fastify({
  logger: true,
});
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

fastify.register(fastifyStatic, {
  root: path.join(__dirname, '../public')
});

fastify.register(fastifyView, {
  engine: {
    ejs: ejs,
  },
  root: './views',
  layout: 'layout.ejs',
});

fastify.register(fastifyAuth0, {
  domain: process.env.AUTH0_DOMAIN as string,
  clientId: process.env.AUTH0_CLIENT_ID as string,
  clientSecret: process.env.AUTH0_CLIENT_SECRET as string,
  appBaseUrl: process.env.APP_BASE_URL as string,
  sessionSecret: process.env.AUTH0_SESSION_SECRET as string,
});

fastify.get('/', async (request, reply) => {
  const user = await fastify.auth0Client!.getUser({
    request, reply
  });
  return reply.viewAsync('index.ejs', {
    isLoggedIn: !!user, user: user
  });
});

async function hasSessionPreHandler(
  request: FastifyRequest,
  reply: FastifyReply
) {
  const session = await fastify.auth0Client!.getSession({
    request, reply
  });

  if (!session) {
    reply.redirect(`/auth/login?returnTo=${request.url}`);
  }
}

fastify.get(
  '/private',
  { preHandler: hasSessionPreHandler },
  async (request, reply) => {
    const user = await fastify.auth0Client!.getUser({
      request, reply
    });

    return reply.viewAsync('private.ejs', {
      isLoggedIn: !!user,
      user,
    });
  }
);

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

Auth0 AI SDKs

Auth0 AI SDKs to streamline integrating your application with popular agentic frameworks:

Auth0 AI SDK

This SDK provides base abstractions for authentication and authorization in AI applications. It supports:
npm install @auth0/ai

Auth0 AI Components

This library helps to set up the React components that can be used in AI applications using Auth0 for AI Agents. The components are styled using Tailwind CSS. It supports:
  • Tools for getting access tokens for supported social and enterprise identity providers
npx @auth0/ai-components add TokenVault
Below is a code sample showing how to integrate Auth0 token-vault interrupts in a React component. It demonstrates key patterns like submitting messages, managing focus, and handling consent via a TokenVault popup. For more examples, click here.
This React Chat example shows how to integrate streaming with Auth0’s token-vault interrupts: it submits messages, refocuses input after loading, and displays a consent popup when a TokenVault interrupt occurs.
"use client";

import { useQueryState } from "nuqs";
import { FormEventHandler, useEffect, useRef, useState } from "react";
import { TokenVaultConsentPopup } from "@/components/auth0-ai/TokenVault/popup";
import { TokenVaultInterrupt } from "@auth0/ai/interrupts";
import { useStream } from "@langchain/langgraph-sdk/react";

function useFocus() {
  const ref = useRef<HTMLInputElement>(null);
  const focus = () => ref.current?.focus();
  return [ref, focus] as const;
}

export default function Chat() {
  const [threadId, setThreadId] = useQueryState("threadId");
  const [input, setInput] = useState("");
  const thread = useStream({
    apiUrl: `${process.env.NEXT_PUBLIC_URL}/api/langgraph`,
    assistantId: "agent",
    threadId,
    onThreadId: setThreadId,
    onError: (err) => console.error(err),
  });
  const [inputRef, focusInput] = useFocus();

  useEffect(() => {
    if (!thread.isLoading) {
      focusInput();
    }
  }, [thread.isLoading, focusInput]);

  const handleSubmit: FormEventHandler<HTMLFormElement> = (e) => {
    e.preventDefault();
    thread.submit(
      { messages: [{ type: "human", content: input }] },
      {
        optimisticValues: (prev) => ({
          messages: [
            ...(prev?.messages ?? []),
            { type: "human", content: input, id: "temp" },
          ],
        }),
      }
    );
    setInput("");
  };

  return (
    <div>
      {thread.messages
        .filter((m) => m.content && (m.type === "human" || m.type === "ai"))
        .map((m) => (
          <div key={m.id}>
            {m.type === "human" ? "User: " : "AI: "}
            {m.content}
          </div>
        ))}

      {thread.interrupt && TokenVaultInterrupt.isInterrupt(thread.interrupt.value) && (
        <TokenVaultConsentPopup
          interrupt={thread.interrupt.value}
          onFinish={() => thread.submit(null)}
          connectWidget={{
            title: thread.interrupt.value.message,
            description: "Please confirm to continue",
            action: { label: "Proceed" },
          }}
        />
      )}

      <form onSubmit={handleSubmit}>
        <input
          ref={inputRef}
          value={input}
          placeholder="Type something..."
          readOnly={thread.isLoading}
          disabled={thread.isLoading}
          onChange={(e) => setInput(e.target.value)}
        />
      </form>
    </div>
  );
}
This React Chat example illustrates how to integrate AI SDK streaming with Auth0’s token-vault interrupts: it sends messages via the SDK, manages input focus during loading, and prompts users via a consent popup when a TokenVault interrupt is triggered.
"use client";

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

export default function Chat() {
  const [input, setInput] = useState("");
  const { messages, sendMessage, toolInterrupt } = useInterruptions((handler) =>
    useChat({
      transport: new DefaultChatTransport({ api: "/api/ai-sdk" }),
      experimental_throttle: 100,
      generateId,
      onError: handler((error) => console.error("Chat error:", error)),
      sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
    })
  );
  return (
    <div>
      {messages.map((message) => (
        <div key={message.id}>
          {message.role === "user" ? "User: " : "AI: "}
          {(message?.parts[message.parts.length - 1] as any)?.text}
        </div>
      ))}

      {TokenVaultInterrupt.isInterrupt(toolInterrupt) && (
        <TokenVaultConsentPopup
          interrupt={toolInterrupt}
          connectWidget={{
            title: `Requested by: "${toolInterrupt.toolCall.name}"`,
            description: "Description...",
            action: { label: "Check" },
          }}
        />
      )}

      <form
        onSubmit={(e) => {
          e.preventDefault();
          sendMessage({ text: input });
          setInput("");
        }}
      >
        <input
          value={input}
          placeholder="Say something..."
          onChange={(e) => setInput(e.target.value)}
          autoFocus
        />
      </form>
    </div>
  );
}

Redis Store for Auth0 AI

This SDK provides a secure Redis-based data store implementation for use with the Auth0 AI SDKs. It supports:
  • Securely encrypting data before storing it in Redis
  • Organizing keys using namespaces
  • Setting expiration times for stored data
npm install @auth0/ai-redis