---
url: https://haihv.github.io/valifetch/api/auth/functions/bearerAuth.md
---

# Function: bearerAuth()

> **bearerAuth**(`getToken`): [`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md)

Defined in: [src/auth.ts:69](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L69)

Returns a `beforeRequest` hook that adds an `Authorization: Bearer <token>`
header before every request.

If `getToken()` returns `null` or `undefined` the header is left unset,
allowing unauthenticated requests to pass through.

## Parameters

### getToken

() => `string` | `null` | `undefined`

Synchronous getter for the current access token.

## Returns

[`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md)

A `beforeRequest` hook that sets the `Authorization` header.

## Example

```ts
import valifetch from 'valifetch';
import { bearerAuth } from 'valifetch/auth';

const api = valifetch.create({
  hooks: { beforeRequest: [bearerAuth(() => localStorage.getItem('token'))] },
});
```
