> For the complete documentation index, see [llms.txt](https://docs.chord.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chord.co/chord-oms/developer-tools/next-js/sdk-reference/useauth.md).

# useAuth

{% hint style="info" %}
**This page's documentation only applies to Chord's** [**Next.js starter**](https://github.com/chordcommerce/nextjs-starter-autonomy) **prior to the release of the** [React](/chord-oms/developer-tools/react.md)**. The Next.js starter now uses the React SDK and does not use the methods documented on this page. Check out the** [**React SDK Reference**](https://docs-beta.chord.co/chord-ui/module-react-autonomy) **for complete documentation, and the** [React SDK Migration Guide](/chord-oms/developer-tools/next-js/guides/react-sdk-migration-guide.md)**for details on how to upgrade.**
{% endhint %}

The `useAuth` hook returns information about the current authentication session, and functions for logging in and logging out. Chord supports passwordless authentication with [Magic](https://magic.link/).

## Example

```javascript
import { useAuth } from '~/hooks/actions'

const AccountPage = () => {
  const { isLoggedIn } = useAuth()
  if (!isLoggedIn) return

  // return account page
}
```

## Returns

The `useAuth` hook returns an object with these properties:

| Property         | Description                                                                                                                                                |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `isLoggedIn`     | A boolean indicating whether the user is currently logged in.                                                                                              |
| `isFetching`     | A boolean indicating whether the user's authentication status is currently being fetched.                                                                  |
| `token`          | A string representing the user's authentication token. This token is automatically appended to Chord OMS API requests when the user has an active session. |
| `getToken`       | A function that retrieves an authentication token for the current user session.                                                                            |
| `handleCallback` | A function that completes the login process, when the user is redirected back to the site after clicking a link in their email.                            |
| `login`          | A function that should be called when a user submits a login form.                                                                                         |
| `logout`         | A function that terminates the user's current session.                                                                                                     |

## Functions

### getToken

The `getToken` function retrieves an authentication token for the current user session, and adds it the Redux store. While you are unlikely to need the token directly, since the SDK automatically appends it to relevant Chord API requests, you can use this function to check whether the user's session is still active. If the user's session has expired, `getToken` will throw an error.

You may choose to call `getToken` on page load or when a user visits a protected route (like an account page) to check that their session has not expired since the last time you checked.

**Arguments:**

None.

**Returns:**

`Promise<void>`: A Promise that resolves when the token has been added to the Redux store.

**Example:**

```javascript
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import { useAuth } from '~/hooks/actions'

const PrivateRoute = ({ children }) => {
  const { getToken, isLoggedIn, isFetching } = useAuth()
  const router = useRouter()

  useEffect(() => {
    const checkStatus = async () => {
      try {
        await getToken()
      } catch (error) {
        router.push('/login')
      }
    }

    if (!isLoggedIn) checkStatus()
  }, [isLoggedIn, getToken, router])

  if (!isLoggedIn && isFetching) {
    // return loading animation
  }

  if (!isLoggedIn && !isFetching) {
    //return null
  }

  return children
}
```

### handleCallback

The `handleCallback` function completes the login process, when the user is redirected back to the site after clicking a link in their email. The SDK calls this function automatically when the Magic url parameter is detected on page load, so you are unlikely to need to call this function.

**Arguments:**

None.

**Returns:**

`Promise<void>`: A Promise that resolves when the token has been added to the Redux store.

**Example:**

```javascript
import { useEffect } from 'react'
import { useAuth } from '~/hooks/actions'

const Page = ({ children }) => {
  const { handleCallback } = useAuth()

  useEffect(() => {
    const handle = async () => {
      try {
        await handleCallback()
      } catch (error) {
        console.error('Invalid callback token.')
      }
    }
    handle()
  }, [])

  // return page
}
```

### login

The `login` function should be called when a user submits a login form. It will trigger an email to the user for verification.

**Arguments:**

`login({ email, showUI, redirectURI })`

| Argument       | Type                                                  | Description                                                                                                                               |
| -------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `email`        | String                                                | The user's email address.                                                                                                                 |
| `showUI?`      | Boolean (optional, defaults to `false`)               | Controls whether Magic's default UI will display from when `login` is called until the user clicks the link they've received in an email. |
| `redirectURI?` | String (optional, defaults to `window.location.href`) | The URL that the user will be redirected to when they click the link they've received in an email.                                        |

**Returns:**

`Promise<void>`

**Example:**

```javascript
import { useRouter } from 'next/router'
import { useAuth } from '~/hooks/actions'

const LoginForm = () => {
  const { login } = useAuth()
  const router = useRouter()

  const onSubmit = async ({ email }) => {
    try {
      await login({ email })
      router.push('/some-private-route')
    } catch (error) {
      console.error('Login unsuccessful.')
    }
  }

  // return login form
}
```

### logout

The `logout` function terminates the user's current session.

**Arguments:**

None.

**Returns:**

`Promise<void>`: A Promise that resolves when the session has been cleared.

**Example:**

```javascript
import { useAuth } from '~/hooks/actions'

const LogoutButton = () => {
  const { logout } = useAuth()

  const handleLogout = async () => {
    try {
      await logout()
    } catch(error) {
      console.error('Logout unsuccessful.')
    }
  }

  return <button onClick={handleLogout}>Logout</button>
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.chord.co/chord-oms/developer-tools/next-js/sdk-reference/useauth.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
