---
title: "MastraAuthAuth0 Class | Auth"
description: "Documentation for the MastraAuthAuth0 class, which authenticates Mastra applications using Auth0 authentication."
packages:
  - "@mastra/auth-auth0"
  - "@mastra/client-js"
  - "@mastra/core"
---

import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";

# MastraAuthAuth0 Class

The `MastraAuthAuth0` class provides authentication for Mastra using Auth0. It verifies incoming requests using Auth0-issued JWT tokens and integrates with the Mastra server using the `auth` option.

## Prerequisites

This example uses Auth0 authentication. Make sure to:

1. Create an Auth0 account at [auth0.com](https://auth0.com/)
2. Set up an Application in your Auth0 Dashboard
3. Configure an API in your Auth0 Dashboard with an identifier (audience)
4. Configure your application's allowed callback URLs, web origins, and logout URLs

```env title=".env"
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-identifier
```

> **Note:** You can find your domain in the Auth0 Dashboard under Applications > Settings. The audience is the identifier of your API configured in Auth0 Dashboard > APIs.

> For detailed setup instructions, refer to the [Auth0 quickstarts](https://auth0.com/docs/quickstarts) for your specific platform.

## Installation

Before you can use the `MastraAuthAuth0` class you have to install the `@mastra/auth-auth0` package.

```bash
npm install @mastra/auth-auth0@beta
```

## Usage examples

### Basic usage with environment variables

```typescript {2,6} title="src/mastra/index.ts"
import { Mastra } from "@mastra/core";
import { MastraAuthAuth0 } from "@mastra/auth-auth0";

export const mastra = new Mastra({
  server: {
    auth: new MastraAuthAuth0(),
  },
});
```

### Custom configuration

```typescript {2,6-9} title="src/mastra/index.ts"
import { Mastra } from "@mastra/core";
import { MastraAuthAuth0 } from "@mastra/auth-auth0";

export const mastra = new Mastra({
  server: {
    auth: new MastraAuthAuth0({
      domain: process.env.AUTH0_DOMAIN,
      audience: process.env.AUTH0_AUDIENCE,
    }),
  },
});
```

## Configuration

### User Authorization

By default, `MastraAuthAuth0` allows all authenticated users who have valid Auth0 tokens for the specified audience. The token verification ensures that:

1. The token is properly signed by Auth0
2. The token is not expired
3. The token audience matches your configured audience
4. The token issuer matches your Auth0 domain

To customize user authorization, provide a custom `authorizeUser` function:

```typescript title="src/mastra/auth.ts"
import { MastraAuthAuth0 } from "@mastra/auth-auth0";

const auth0Provider = new MastraAuthAuth0({
  authorizeUser: async (user) => {
    // Custom authorization logic
    return user.email?.endsWith("@yourcompany.com") || false;
  },
});
```

:::info

Visit [MastraAuthAuth0](/reference/v1/auth/auth0) for all available configuration options.

:::

## Client-side setup

When using Auth0 auth, you'll need to set up the Auth0 React SDK, authenticate users, and retrieve their access tokens to pass to your Mastra requests.

### Setting up Auth0 React SDK

First, install and configure the Auth0 React SDK in your application:

```bash
npm install @auth0/auth0-react
```

```typescript title="src/auth0-provider.tsx"
import React from 'react';
import { Auth0Provider } from '@auth0/auth0-react';

const Auth0ProviderWithHistory = ({ children }) => {
  return (
    <Auth0Provider
      domain={process.env.REACT_APP_AUTH0_DOMAIN}
      clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: window.location.origin,
        audience: process.env.REACT_APP_AUTH0_AUDIENCE,
        scope: "read:current_user update:current_user_metadata"
      }}
    >
      {children}
    </Auth0Provider>
  );
};

export default Auth0ProviderWithHistory;
```

### Retrieving access tokens

Use the Auth0 React SDK to authenticate users and retrieve their access tokens:

```typescript title="lib/auth.ts"
import { useAuth0 } from "@auth0/auth0-react";

export const useAuth0Token = () => {
  const { getAccessTokenSilently } = useAuth0();

  const getAccessToken = async () => {
    const token = await getAccessTokenSilently();
    return token;
  };

  return { getAccessToken };
};
```

> Refer to the [Auth0 React SDK documentation](https://auth0.com/docs/libraries/auth0-react) for more authentication methods and configuration options.

## Configuring `MastraClient`

When `auth` is enabled, all requests made with `MastraClient` must include a valid Auth0 access token in the `Authorization` header:

```typescript title="lib/mastra/mastra-client.ts"
import { MastraClient } from "@mastra/client-js";

export const createMastraClient = (accessToken: string) => {
  return new MastraClient({
    baseUrl: "https://<mastra-api-url>",
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });
};
```

> **Note:** The access token must be prefixed with `Bearer` in the Authorization header.

:::info

Visit [Mastra Client SDK](/docs/v1/server/mastra-client) for more configuration options.

:::

### Making authenticated requests

Once `MastraClient` is configured with the Auth0 access token, you can send authenticated requests:

<Tabs>
  <TabItem value="react" label="React">
    ```tsx title="src/components/mastra-api-test.tsx" copy
    import React, { useState } from 'react';
    import { useAuth0 } from '@auth0/auth0-react';
    import { MastraClient } from '@mastra/client-js';

    export const MastraApiTest = () => {
      const { getAccessTokenSilently } = useAuth0();
      const [result, setResult] = useState(null);

      const callMastraApi = async () => {
        const token = await getAccessTokenSilently();

        const mastra = new MastraClient({
          baseUrl: "http://localhost:4111",
          headers: {
            Authorization: `Bearer ${token}`
          }
        });

        const weatherAgent = mastra.getAgent("weatherAgent");
        const response = await weatherAgent.generate({
          messages: "What's the weather like in New York"
        });

        setResult(response.text);
      };

      return (
        <div>
          <button onClick={callMastraApi}>
            Test Mastra API
          </button>

          {result && (
            <div className="result">
              <h6>Result:</h6>
              <pre>{result}</pre>
            </div>
          )}
        </div>
      );
    };
    ```

  </TabItem>
  <TabItem value="curl" label="cURL">
    ```bash copy
    curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer <your-auth0-access-token>" \
      -d '{
        "messages": "Weather in London"
      }'
    ```
  </TabItem>
</Tabs>
