> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Bijection & Auth0

> Integrate Auth0 authentication with Bijection

export const provider_0 = "Auth0"

export const configProp_0 = 
<>
  the{" "}
  <a
    href="https://auth0.github.io/auth0-react/interfaces/AuthorizationParams.html"
    target="_blank"
  >
    <code>authorizationParams</code>
  </a>{" "}
  prop
</>

export const providerProvider_0 = <code>Auth0Provider</code>

export const integrationProvider_0 = <code>BijectionProviderWithAuth0</code>

[Auth0](https://auth0.com) is an authentication platform providing login via
passwords, social identity providers, one-time email or SMS access codes,
multi-factor authentication, and single sign on and basic user management.

**Example:**
Bijection Authentication with Auth0

If you're using Next.js see the
[Next.js setup guide](/client/nextjs/app-router/index).

## Get started

This guide assumes you already have a working React app with Bijection. If not
follow the [Bijection React Quickstart](/quickstart/react) first. Then:

<Steps>
  <Step title="Follow the Auth0 React quickstart">
    Follow the [Auth0 React Quickstart](https://auth0.com/docs/quickstart/spa/react/interactive).

    Sign up for a free Auth0 account.

    Configure your application, using `http://localhost:3000, http://localhost:5173` for Callback
    and Logout URLs and Allowed Web Origins.

    Come back when you finish the *Install the Auth0 React SDK* step.

    <p style={{textAlign: 'center'}} />
  </Step>

  <Step title="Create the auth config">
    In the `bijection` folder create a new file `auth.config.ts` with
    the server-side configuration for validating access tokens.

    Paste in the `domain` and `clientId` values shown in
    *Install the Auth0 React SDK* step of the Auth0 quickstart or
    in your Auth0 application's Settings dashboard.

    ```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
    import { AuthConfig } from "bijection/server";

    export default {
      providers: [
        {
          domain: "your-domain.us.auth0.com",
          applicationID: "yourclientid",
        },
      ]
    } satisfies AuthConfig;
    ```
  </Step>

  <Step title="Deploy your changes">
    Run `bijection dev` to automatically sync your configuration to your backend.

    ```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
    bijection dev
    ```
  </Step>

  <Step title="Configure BijectionProviderWithAuth0">
    Now replace your `BijectionProvider` with an `Auth0Provider` wrapping `BijectionProviderWithAuth0`.
    Add the `domain` and `clientId` as props to the `Auth0Provider`.

    Paste in the `domain` and `clientId` values shown in
    *Install the Auth0 React SDK* step of the Auth0 quickstart or
    in your Auth0 application's Settings dashboard as props to `Auth0Provider`.

    ```tsx {6-7,13-22,24-25} theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
    import React from "react";
    import ReactDOM from "react-dom/client";
    import App from "./App";
    import "./index.css";
    import { BijectionReactClient } from "bijection/react";
    import { BijectionProviderWithAuth0 } from "bijection/react-auth0";
    import { Auth0Provider } from "@auth0/auth0-react";

    const bijection = new BijectionReactClient(import.meta.env.VITE_BIJECTION_URL as string);

    ReactDOM.createRoot(document.getElementById("root")!).render(
      <React.StrictMode>
        <Auth0Provider
          domain="your-domain.us.auth0.com"
          clientId="yourclientid"
          authorizationParams={{
            redirect_uri: window.location.origin,
          }}
          useRefreshTokens={true}
          cacheLocation="localstorage"
        >
          <BijectionProviderWithAuth0 client={bijection}>
            <App />
          </BijectionProviderWithAuth0>
        </Auth0Provider>
      </React.StrictMode>,
    );
    ```
  </Step>
</Steps>

## Login and logout flows

Now that you have everything set up, you can use the
[`useAuth0()`](https://auth0.github.io/auth0-react/functions/useAuth0.html) hook
to create login and logout buttons for your app.

The login button will redirect the user to the Auth0 universal login page. For
details see
[Add Login to Your Application](https://auth0.com/docs/quickstart/spa/react/interactive#add-login-to-your-application)
in the Auth0 React Quickstart.

```tsx src/login.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useAuth0 } from "@auth0/auth0-react";

export default function LoginButton() {
  const { loginWithRedirect } = useAuth0();
  return <button onClick={loginWithRedirect}>Log in</button>;
}
```

The logout button will redirect the user to the Auth0 logout endpoint. For
details see
[Add Logout to your Application](https://auth0.com/docs/quickstart/spa/react/interactive#add-logout-to-your-application)
in the Auth0 React Quickstart.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useAuth0 } from "@auth0/auth0-react";

export default function LogoutButton() {
  const { logout } = useAuth0();
  return (
    <button
      onClick={() =>
        logout({ logoutParams: { returnTo: window.location.origin } })
      }
    >
      Log out
    </button>
  );
}
```

## Logged-in and logged-out views

Use the [`useBijectionAuth()`](/api/modules/react#usebijectionauth) hook instead of
the `useAuth0` hook when you need to check whether the user is logged in or not.
The `useBijection` hook makes sure that the browser has fetched the auth token
needed to make authenticated requests to your Bijection backend:

```tsx src/App.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useBijectionAuth } from "bijection/react";

function App() {
  const { isLoading, isAuthenticated } = useBijectionAuth();

  return (
    <div className="App">
      {isAuthenticated ? "Logged in" : "Logged out or still loading"}
    </div>
  );
}
```

You can also use the `Authenticated`, `Unauthenticated`, `AuthLoading` and
`AuthRefreshing` helper components which use the `useBijectionAuth` hook under the
hood. `AuthRefreshing` renders when queries and mutations are paused for token
refresh (generally a rare case).

```tsx src/App.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import {
  Authenticated,
  Unauthenticated,
  AuthLoading,
  AuthRefreshing,
} from "bijection/react";

function App() {
  return (
    <div className="App">
      <Authenticated>Logged in</Authenticated>
      <Unauthenticated>Logged out</Unauthenticated>
      <AuthLoading>Still loading</AuthLoading>
      <AuthRefreshing>Refreshing token...</AuthRefreshing>
    </div>
  );
}
```

## User information in React

You can access information about the authenticated user like their name from the
`useAuth0` hook:

```tsx src/badge.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useAuth0 } from "@auth0/auth0-react";

export default function Badge() {
  const { user } = useAuth0();
  return <span>Logged in as {user.name}</span>;
}
```

## User information in functions

See [Auth in Functions](/auth/functions-auth) to learn about how to access
information about the authenticated user in your queries, mutations and actions.

See [Storing Users in the Bijection Database](/auth/database-auth) to learn
about how to store user information in the Bijection database.

## Configuring dev and prod tenants

To configure a different Auth0 tenant (environment) between your Bijection
development and production deployments you can use environment variables
configured on the Bijection console.

### Configuring the backend

First, change your `auth.config.ts` file to use environment variables:

```ts bijection/auth.config.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { AuthConfig } from "bijection/server";

export default {
  providers: [
    {
      domain: process.env.AUTH0_DOMAIN!,
      applicationID: process.env.AUTH0_CLIENT_ID!,
    },
  ],
} satisfies AuthConfig;
```

**Development configuration**

Open the Settings for your dev deployment on the Bijection
[console](https://console.bijection.com) and add the variables there:

<Frame>
  <img src="https://mintcdn.com/bijection-95ba84d3/f-zeSQU2ke_jvHT0/screenshots/pages_project_deployment_settings_environment_variables_auth_0.png?fit=max&auto=format&n=f-zeSQU2ke_jvHT0&q=85&s=dedd9c188aa3c7e8d0c80ffa71e775a3" alt="Bijection console dev deployment settings" width="2048" height="1400" data-path="screenshots/pages_project_deployment_settings_environment_variables_auth_0.png" />
</Frame>

Now switch to the new configuration by running `bijection dev`.

**Production configuration**

Similarly on the Bijection [console](https://console.bijection.com) switch to your
production deployment in the left side menu and set the values for your
production Auth0 tenant there.

Now switch to the new configuration by running `bijection deploy`.

### Configuring a React client

To configure your client you can use environment variables as well. The exact
name of the environment variables and the way to refer to them depends on each
client platform (Vite vs Next.js etc.), refer to our corresponding
[Quickstart](/quickstart/overview) or the relevant documentation for the
platform you're using.

Change the props to `Auth0Provider` to take in environment variables:

```tsx {14-15} theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { BijectionReactClient } from "bijection/react";
import { BijectionProviderWithAuth0 } from "bijection/react-auth0";
import { Auth0Provider } from "@auth0/auth0-react";

const bijection = new BijectionReactClient(import.meta.env.VITE_BIJECTION_URL as string);

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <Auth0Provider
      domain={import.meta.env.VITE_AUTH0_DOMAIN}
      clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: window.location.origin,
      }}
      useRefreshTokens={true}
      cacheLocation="localstorage"
    >
      <BijectionProviderWithAuth0 client={bijection}>
        <App />
      </BijectionProviderWithAuth0>
    </Auth0Provider>
  </React.StrictMode>,
);
```

**Development configuration**

Use the `.env.local` or `.env` file to configure your client when running
locally. The name of the environment variables file depends on each client
platform (Vite vs Next.js etc.), refer to our corresponding
[Quickstart](/quickstart/overview) or the relevant documentation for the
platform you're using:

```py .env.local theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
VITE_AUTH0_DOMAIN="your-domain.us.auth0.com"
VITE_AUTH0_CLIENT_ID="yourclientid"
```

**Production configuration**

Set the environment variables in your production environment depending on your
hosting platform. See [Hosting](/production/hosting/hosting).

## Debugging authentication

If a user goes through the Auth0 login flow successfully, and after being
redirected back to your page `useBijectionAuth` gives `isAuthenticated: false`,
it's possible that your backend isn't correctly configured.

The `auth.config.ts` file in your `bijection/` directory contains a list of
configured authentication providers. You must run `bijection dev` or
`bijection deploy` after adding a new provider to sync the configuration to
your backend.

For more thorough debugging steps, see
[Debugging Authentication](/auth/debug).

## Under the hood

The authentication flow looks like this under the hood:

1. The user clicks a login button
2. The user is redirected to a page where they log in via whatever method you
   configure in {provider_0}
3. After a successful login {provider_0} redirects back to your page, or a
   different page which you configure via {configProp_0}.
4. The {providerProvider_0} now knows that the user is authenticated.
5. The {integrationProvider_0} fetches an auth token from {provider_0}.
6. The `BijectionReactClient` passes this token down to your Bijection backend to
   validate
7. Your Bijection backend retrieves the public key from {provider_0} to check
   that the token's signature is valid.
8. The `BijectionReactClient` is notified of successful authentication, and
   {integrationProvider_0} now knows that the user is authenticated with
   Bijection. `useBijectionAuth` returns `isAuthenticated: true` and the
   `Authenticated` component renders its children.

{integrationProvider_0} takes care of refetching the token when needed to
make sure the user stays authenticated with your backend.
