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

# getAccessToken

> Retrieve access tokens with automatic refresh

The `getAccessToken` method retrieves the access token for the currently authenticated user, automatically refreshing it if expired and a refresh token is available.

## Method Signatures

<CodeGroup>
  ```typescript App Router theme={null}
  // Server Components, Server Actions, Route Handlers
  await auth0.getAccessToken(
    options?: GetAccessTokenOptions
  ): Promise<AccessTokenResponse>
  ```

  ```typescript Pages Router theme={null}
  // getServerSideProps, API Routes
  await auth0.getAccessToken(
    req: IncomingMessage | NextApiRequest,
    res: ServerResponse | NextApiResponse,
    options?: GetAccessTokenOptions
  ): Promise<AccessTokenResponse>
  ```

  ```typescript Middleware theme={null}
  // middleware.ts
  await auth0.getAccessToken(
    req: NextRequest,
    res: NextResponse,
    options?: GetAccessTokenOptions
  ): Promise<AccessTokenResponse>
  ```
</CodeGroup>

## Parameters

<ParamField path="req" type="IncomingMessage | NextApiRequest | NextRequest">
  The request object (Pages Router and middleware only)
</ParamField>

<ParamField path="res" type="ServerResponse | NextApiResponse | NextResponse">
  The response object (Pages Router and middleware only)
</ParamField>

<ParamField path="options" type="GetAccessTokenOptions">
  Optional configuration for token retrieval

  ```typescript theme={null}
  interface GetAccessTokenOptions {
    refresh?: boolean;
    audience?: string;
    scope?: string;
  }
  ```

  <Accordion title="Options Details">
    * `refresh`: Force token refresh even if not expired
    * `audience`: Request token for specific API audience
    * `scope`: Request specific scopes (for MRRT)
  </Accordion>
</ParamField>

## Returns

Returns a `Promise` that resolves to:

```typescript theme={null}
interface AccessTokenResponse {
  token: string;        // The access token
  expiresAt: number;    // Expiration timestamp (seconds since epoch)
  scope?: string;       // Granted scopes
  token_type?: string;  // Token type (usually "Bearer")
  audience?: string;    // Token audience
}
```

## Usage Examples

### App Router

<CodeGroup>
  ```typescript Server Component theme={null}
  import { auth0 } from '@/lib/auth0';

  export default async function Page() {
    const { token } = await auth0.getAccessToken();

    const response = await fetch('https://api.example.com/data', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    const data = await response.json();
    return <div>{JSON.stringify(data)}</div>;
  }
  ```

  ```typescript Route Handler theme={null}
  import { NextResponse } from 'next/server';
  import { auth0 } from '@/lib/auth0';

  export async function GET() {
    try {
      const { token } = await auth0.getAccessToken();

      const response = await fetch('https://api.example.com/data', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });

      const data = await response.json();
      return NextResponse.json(data);
    } catch (error) {
      return NextResponse.json(
        { error: 'Failed to get access token' },
        { status: 401 }
      );
    }
  }
  ```

  ```typescript Server Action theme={null}
  import { auth0 } from '@/lib/auth0';

  export async function callAPI() {
    'use server';
    
    const { token } = await auth0.getAccessToken();

    const response = await fetch('https://api.example.com/data', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    return response.json();
  }
  ```
</CodeGroup>

### Pages Router

<CodeGroup>
  ```typescript API Route theme={null}
  import type { NextApiRequest, NextApiResponse } from 'next';
  import { auth0 } from '@/lib/auth0';

  export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
  ) {
    try {
      const { token } = await auth0.getAccessToken(req, res);

      const response = await fetch('https://api.example.com/data', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });

      const data = await response.json();
      res.json(data);
    } catch (error) {
      res.status(401).json({ error: 'Unauthorized' });
    }
  }
  ```

  ```typescript getServerSideProps theme={null}
  import type { GetServerSideProps } from 'next';
  import { auth0 } from '@/lib/auth0';

  export const getServerSideProps: GetServerSideProps = async (ctx) => {
    try {
      const { token } = await auth0.getAccessToken(ctx.req, ctx.res);

      const response = await fetch('https://api.example.com/data', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });

      const data = await response.json();

      return { props: { data } };
    } catch (error) {
      return { props: { error: 'Failed to fetch data' } };
    }
  };
  ```
</CodeGroup>

### Middleware

```typescript middleware.ts theme={null}
import { NextRequest, NextResponse } from 'next/server';
import { auth0 } from '@/lib/auth0';

export async function middleware(request: NextRequest) {
  const authRes = await auth0.middleware(request);

  if (request.nextUrl.pathname.startsWith('/auth')) {
    return authRes;
  }

  try {
    const { token } = await auth0.getAccessToken(request, authRes);
    
    // Token is available and refreshed if needed
    console.log('Access token expires at:', token.expiresAt);
  } catch (error) {
    // Redirect to login if token retrieval fails
    return NextResponse.redirect(
      new URL('/auth/login', request.url)
    );
  }

  return authRes;
}
```

## Advanced Usage

### Force Token Refresh

Force a token refresh even if not expired:

```typescript theme={null}
const { token } = await auth0.getAccessToken({
  refresh: true
});
```

<Note>
  This is useful when user permissions or scopes have changed and you need to ensure the token reflects the latest state.
</Note>

### Multi-Resource Refresh Tokens (MRRT)

Request tokens for different audiences:

```typescript theme={null}
// Default audience
const defaultToken = await auth0.getAccessToken();

// Specific audience
const apiToken = await auth0.getAccessToken({
  audience: 'https://api.example.com'
});

// With additional scopes
const adminToken = await auth0.getAccessToken({
  audience: 'https://admin.example.com',
  scope: 'read:admin write:admin'
});
```

<Warning>
  When using MRRT, ensure your Auth0 Application's Refresh Token Policies are configured with the required audiences.
</Warning>

### Token Refresh Buffer

Refresh tokens proactively before expiration:

```typescript lib/auth0.ts theme={null}
import { Auth0Client } from '@auth0/nextjs-auth0/server';

export const auth0 = new Auth0Client({
  tokenRefreshBuffer: 60 // Refresh 60 seconds before expiry
});
```

### Race Condition Mitigation

Check token expiry before critical operations:

```typescript theme={null}
const session = await auth0.getSession();

if (!session?.tokenSet?.expiresAt) {
  throw new Error('No session');
}

const BUFFER = 30; // 30 seconds
const expiresIn = session.tokenSet.expiresAt - Date.now() / 1000;

let token = session.tokenSet.accessToken;

if (expiresIn < BUFFER) {
  // Token expires soon, refresh it
  const refreshed = await auth0.getAccessToken({ refresh: true });
  token = refreshed.token;
}

// Use fresh token for API call
await fetch('https://api.example.com/critical', {
  headers: { Authorization: `Bearer ${token}` }
});
```

## Error Handling

The method throws `AccessTokenError` when:

* User has no active session
* Token refresh fails
* MFA is required (throws `MfaRequiredError`)

```typescript theme={null}
import { AccessTokenError, MfaRequiredError } from '@auth0/nextjs-auth0/server';

try {
  const { token } = await auth0.getAccessToken();
} catch (error) {
  if (error instanceof MfaRequiredError) {
    // Handle MFA challenge
    console.log('MFA required:', error.mfa_token);
  } else if (error instanceof AccessTokenError) {
    // Handle other token errors
    console.error('Token error:', error.code, error.message);
  }
}
```

## Session Persistence

<Note>
  When tokens are refreshed, the updated token set is automatically persisted to the session.
</Note>

<Warning>
  **Server Components cannot set cookies.** Calling `getAccessToken()` in a Server Component will refresh the token if expired, but the updated token set will **not** be persisted.

  To ensure token updates are saved, call `getAccessToken(req, res)` in middleware or API routes.
</Warning>

## Refresh Token Rotation

<Warning>
  If your Auth0 application uses **Refresh Token Rotation**, configure an overlap period in the Auth0 Dashboard to prevent race conditions when multiple requests attempt to refresh tokens simultaneously.

  Navigate to: **Applications > Advanced Settings > OAuth**
</Warning>

## Important Notes

<Note>
  The response includes:

  * `token`: The access token string
  * `expiresAt`: Token expiration as seconds since Unix epoch
  * `scope`: Granted scopes (if available)
  * `token_type`: Usually "Bearer"
  * `audience`: Token audience (if specified)
</Note>

<Note>
  For Pages Router middleware, pass both `request` and `response` objects to ensure refreshed tokens can be read in the same request:

  ```typescript theme={null}
  const { token } = await auth0.getAccessToken(request, authRes);
  ```
</Note>

## Related Methods

<CardGroup cols={2}>
  <Card title="getSession" icon="id-card" href="/server/get-session">
    Get full session data
  </Card>

  <Card title="updateSession" icon="pen-to-square" href="/server/update-session">
    Update session data
  </Card>
</CardGroup>
