---
title: "OAuthHandler"
description: "OAuthHandler"
url: "https://www.contentstack.com/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler"
product: "Contentstack"
doc_type: "guide"
audience:
  - developers
  - admins
version: "current"
last_updated: "2026-11-22"
---

# OAuthHandler

## OAuthHandler

OAuthHandler runs the Open Authorization (OAuth) sign-in of a JavaScript Management SDK client and holds its tokens. Use this class to

*   build the URL where the user signs in and approves your app
*   exchange the authorization code from the redirect for an access token and a refresh token
*   refresh, read, restore or clear the tokens
*   revoke the app authorization of the signed-in user

Get a handler from the [oauth](/docs/developers/sdks/content-management-sdk/javascript/reference/contentstackclient#contentstackclient-oauth) method of the [ContentstackClient](/docs/developers/sdks/content-management-sdk/javascript/reference/contentstackclient) class, for example client.oauth({ appId: '<APP\_ID>', clientId: '<CLIENT\_ID>', redirectUri: '<REDIRECT\_URI>' }).

## Class-Level Notes

**The sign-in flow.** The four steps below sign a user in:

1.  Call [authorize](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-authorize) and open the URL it resolves to in a browser.
2.  The user signs in and approves the app. Contentstack redirects to your redirect URI with the authorization code in the code query parameter.
3.  Pass the authorization code to [exchangeCodeForToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-exchangecodefortoken), or pass the whole redirect URL to [handleRedirect](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-handleredirect).
4.  Send requests with the same client. The SDK adds authorization: Bearer <access token> to every request that includes no authtoken or authorization header.

**Proof Key for Code Exchange (PKCE).**

*   Without a clientSecret, the handler creates a code verifier when you call client.oauth(). authorize sends a challenge calculated from it, and exchangeCodeForToken sends the verifier.
*   In Node.js the verifier lives only in that handler object. Call authorize and exchangeCodeForToken on the same handler. A handler from another client.oauth() call has another verifier, so its exchange fails.
*   In a browser, the SDK also keeps the verifier in sessionStorage for 10 minutes, under a key that the SDK builds from appId, clientId and redirectUri. A handler created after the redirect with the same three values reuses it. The SDK removes the stored verifier after an exchange, whether it succeeds or fails.
*   With a clientSecret, the handler skips PKCE and sends the secret instead.

**Token storage.**

*   The handler stores the tokens on the client, in client.axiosInstance.oauth, not on the handler. Every handler of one client reads and writes the same tokens.
*   Each client.oauth() call overwrites the stored appId, clientId and redirectUri of the client.
*   The SDK stores the expiry time as the current time plus expires\_in minus 60 seconds, in milliseconds.

**Hosts.**

*   The sign-in page uses the app host that matches the API host of the client, for example app.contentstack.com for api.contentstack.io and eu-app.contentstack.com for the eu region.
*   Token and authorization requests go to the Developer Hub host, for example developerhub-api.contentstack.com or eu-developerhub-api.contentstack.com.
*   A client created with endpoint uses that endpoint as the host of the sign-in page.

**Default headers after OAuth requests.**

*   **Known issue:** [exchangeCodeForToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-exchangecodefortoken), [refreshAccessToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-refreshaccesstoken) and [handleRedirect](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-handleredirect) replace the default headers of the client with a form Content-Type. Later requests then send JSON bodies as form data, and lose the X-User-Agent and User-Agent headers. Save client.axiosInstance.defaults.headers before the call and assign it back after the call resolves.
*   [getOauthAppAuthorization](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-getoauthappauthorization), [revokeOauthAppAuthorization](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-revokeoauthappauthorization) and [logout](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-logout) replace the default headers of the client with authorization, organization\_uid and Content-type: application/json. After logout, the client keeps sending the revoked access token. Create a new client to sign in again.

**Expired access tokens.**

*   **Known issue:** When the stored access token has expired, the next request of the client never completes. Refresh the token before [getTokenExpiryTime](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-gettokenexpirytime) passes. After it passes, call [setTokenExpiryTime](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-settokenexpirytime) with a time in the future, then call [refreshAccessToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-refreshaccesstoken).

**Rate limiting and retry.**

*   The token, authorization and revoke requests use the request queue of the client. The retry settings of the client apply to them.

**Additional Resource:** For more information on the retry settings and their defaults, refer to the [Contentstack](/docs/developers/sdks/content-management-sdk/javascript/reference/contentstack) documentation.

## Capability Matrix

Capability

Supported

Notes / Alternative

Send scope or redirect\_uri in the authorization URL

No

authorize sends only response\_type=code, client\_id and, with PKCE, the challenge. Configure scopes in the app

Refresh an expired token automatically

No

Call refreshAccessToken before getTokenExpiryTime passes

Keep the default headers of the client after a token request

No

Save client.axiosInstance.defaults.headers and assign it back

## Method Index

The four groups below follow the sign-in: start and end it, manage the app authorization, work with the stored tokens, and create PKCE values. Every method is available on the handler that client.oauth() returns.

**Sign in and sign out.** Available on client.oauth(). These methods build the sign-in URL, get and refresh the tokens, and clear them.

Method Name

Returns

Description

[authorize](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-authorize)

The authorization URL to open in a browser.

Builds the URL that starts the sign-in.

[exchangeCodeForToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-exchangecodefortoken)

The token response from Developer Hub.

Exchanges the authorization code for tokens.

[handleRedirect](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-handleredirect)

This method resolves to nothing.

Exchanges the authorization code from a redirect URL.

[refreshAccessToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-refreshaccesstoken)

The token response with the new access token.

Gets a new access token.

[logout](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-logout)

The text Logged out successfully.

Revokes the authorization and clears the tokens.

**Manage the app authorization.** Available on client.oauth(). These methods send requests about the authorization that the user gave the app.

Method Name

Returns

Description

[getOauthAppAuthorization](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-getoauthappauthorization)

The authorization UID of the signed-in user.

Finds the authorization of the current user.

[revokeOauthAppAuthorization](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-revokeoauthappauthorization)

The API response of the revoke request.

Revokes one app authorization.

**Read and restore the tokens.** Available on client.oauth(). These methods read or replace the tokens that the client stores. They send no request.

Method Name

Returns

Description

[getAccessToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-getaccesstoken)

The access token, or undefined.

Returns the stored access token.

[getRefreshToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-getrefreshtoken)

The refresh token, or null.

Returns the stored refresh token.

[getOrganizationUID](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-getorganizationuid)

The organization UID, or null.

Returns the stored organization UID.

[getUserUID](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-getuseruid)

The user UID, or null.

Returns the stored user UID.

[getTokenExpiryTime](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-gettokenexpirytime)

The expiry time in milliseconds, or null.

Returns the stored expiry time.

[setAccessToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-setaccesstoken)

This method returns nothing.

Stores an access token.

[setRefreshToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-setrefreshtoken)

This method returns nothing.

Stores a refresh token.

[setOrganizationUID](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-setorganizationuid)

This method returns nothing.

Stores an organization UID.

[setUserUID](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-setuseruid)

This method returns nothing.

Stores a user UID.

[setTokenExpiryTime](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-settokenexpirytime)

This method returns nothing.

Stores the expiry time.

**Create PKCE values.** Available on client.oauth(). These methods calculate values on the client and send no request.

Method Name

Returns

Description

[generateCodeVerifier](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-generatecodeverifier)

A random code verifier.

Creates a PKCE code verifier.

[generateCodeChallenge](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-generatecodechallenge)

The code challenge for the verifier.

Calculates a PKCE code challenge.

## Class-Level Snippet

The snippet below signs a user in with PKCE, restores the default headers, and lists the organizations of the user.

```
import contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

console.log('Open this URL and sign in:', await oauthHandler.authorize())

// Pass the authorization code from the redirect URI on the command line: node signin.mjs <code>
const code = process.argv[2]

try {
  const savedHeaders = client.axiosInstance.defaults.headers
  await oauthHandler.exchangeCodeForToken(code)
  client.axiosInstance.defaults.headers = savedHeaders

  const organizations = await client.organization().fetchAll()
  organizations.items.forEach((organization) => console.log(organization.uid, organization.name))
} catch (error) {
  // The request failed. The error carries status, error and errorMessage from the response.
  console.error(error.status, error.error, error.errorMessage)
}
```

## Methods

Each method of the OAuthHandler class has its own section below, with its parameters, validation rules, behavior, and examples.

## authorize

authorize builds the URL of the Contentstack page where the user signs in and approves your app.

This method takes no parameters.

```
Returns: Promise<string>. The authorization URL to open in a browser.
ValidationThere is no client-side validation of the app ID or client ID.The returned promise rejects with TypeError when the app host is not a valid URL. A client with an endpoint that is not an absolute URL causes this.BehaviorClient-side only. authorize sends no request. Open the URL in a browser.The URL points at #!/apps/<appId>/authorize on the app host of the client and carries response_type=code and client_id.Without a clientSecret, authorize also adds code_challenge and code_challenge_method=S256. It calculates the challenge from the code verifier of this handler.authorize always sends response_type=code, whatever responseType you passed to client.oauth(). It does not send scope, redirect_uri or state.After sign-in, Contentstack redirects to the redirect URI of the app with the authorization code in the code query parameter. Exchange the authorization code on this same handler with exchangeCodeForToken or handleRedirect.ExampleBasic usage: print the sign-in URLimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  const url = await oauthHandler.authorize()
  // Open the URL in a browser. Contentstack redirects to <REDIRECT_URI>?code=...
  console.log(url)
} catch (error) {
  // The app host of the client does not form a valid URL
  console.error(error.message)
}Build the URL for an app with a client secretimport contentstack from '@contentstack/management'

const client = contentstack.client({ region: 'eu' })
const oauthHandler = client.oauth({
  appId: '<APP_ID>',
  clientId: '<CLIENT_ID>',
  redirectUri: '<REDIRECT_URI>',
  clientSecret: '<CLIENT_SECRET>'
})

try {
  // With a client secret, the URL has no code_challenge
  console.log(await oauthHandler.authorize())
} catch (error) {
  console.error(error.message)
}
```

## exchangeCodeForToken

exchangeCodeForToken exchanges the authorization code from the redirect for an access token and a refresh token, and stores them on the client.

```
Returns: Promise<OAuthResponse>. The token response from Developer Hub.
ValidationThere is no client-side validation. exchangeCodeForToken sends code as it is, even when it is empty.The returned promise rejects with an Error when Developer Hub rejects the request. The error carries status and statusText, and error, errorMessage and errorCode from the response body.Additional Resource: Refer to Content Management API Errors for the full error code list.
BehaviorSends POST /token to the Developer Hub host of the client. The form body holds grant_type=authorization_code, code, redirect_uri and client_id.The body also holds client_secret when the handler has one, else the PKCE code_verifier.On success, stores access_token, refresh_token, organization_uid, user_uid and the expiry time on the client. Every later request of the client sends the access token as authorization: Bearer <token>, unless it carries an authtoken or authorization header.Resolves to the response body as it is, for example access_token, refresh_token, expires_in, organization_uid and user_uid.In a browser, removes the stored PKCE verifier after the request, whether it succeeds or fails. Start a new sign-in with authorize after a failed exchange.exchangeCodeForToken replaces the default headers of the client. The OAuthHandler page describes the effect and the workaround.ExampleBasic usage: exchange the authorization code and restore the default headersimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

console.log('Open this URL and sign in:', await oauthHandler.authorize())
// Pass the authorization code from the redirect URI on the command line: node exchange.mjs <code>
const code = process.argv[2]

try {
  const savedHeaders = client.axiosInstance.defaults.headers
  const tokens = await oauthHandler.exchangeCodeForToken(code)
  client.axiosInstance.defaults.headers = savedHeaders
  console.log(tokens.expires_in, tokens.organization_uid)
} catch (error) {
  // Developer Hub rejected the request. The error carries status, error and errorMessage.
  console.error(error.status, error.error, error.errorMessage)
}
```

Authorization code from the code query parameter.

## generateCodeChallenge

generateCodeChallenge calculates the Proof Key for Code Exchange (PKCE) code challenge for a code verifier.

```
Returns: Promise<string>. The code challenge for the verifier.
ValidationThere is no client-side validation of the verifier format.In Node.js, the returned promise rejects with TypeError when codeVerifier is undefined or null, because the hash function needs a string.BehaviorClient-side only. generateCodeChallenge sends no request.Hashes the verifier with SHA-256 and encodes the hash as URL-safe Base64 without padding, the S256 method of PKCE.In a browser with the Web Crypto API, it uses window.crypto.subtle. Otherwise it uses the Node.js crypto module.authorize calls it with the verifier of the handler and stores the result on the handler. Call it yourself only when you build the authorization URL without the SDK.ExampleBasic usage: calculate the challenge for the verifier of the handlerimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  const challenge = await oauthHandler.generateCodeChallenge(oauthHandler.codeVerifier)
  console.log(challenge)
} catch (error) {
  // Thrown when the verifier is missing, for example on a handler with a client secret
  console.error(error.message)
}
```

Code verifier to hash.

## generateCodeVerifier

generateCodeVerifier creates a random Proof Key for Code Exchange (PKCE) code verifier.

```
Returns: string. A random code verifier.
ValidationThere is no client-side validation. generateCodeVerifier does not enforce the 43 to 128 character range of PKCE. A length of 0 or less returns an empty string.BehaviorClient-side only. generateCodeVerifier sends no request.Picks each character from the letters, digits and the four characters -, ., _ and ~, with Math.random.Returns a new value and does not store it. The handler creates its own verifier when you call client.oauth() without a clientSecret, and authorize and exchangeCodeForToken use that one, not the value that this method returns.ExampleBasic usage: create a verifier and its challengeimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

const verifier = oauthHandler.generateCodeVerifier()
const challenge = await oauthHandler.generateCodeChallenge(verifier)
console.log(verifier.length, challenge)All parameters: create a 64-character verifierimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

const verifier = oauthHandler.generateCodeVerifier(64)
console.log(verifier.length)
```

Number of characters in the verifier.

## getAccessToken

getAccessToken returns the access token that the client stores.

This method takes no parameters.

```
Returns: string. The access token, or undefined.
ValidationThere is no client-side validation. getAccessToken never throws.BehaviorClient-side only. getAccessToken sends no request.Reads the value from the token storage of the client, which every handler of the client shares.Returns undefined when the client stores no access token, for example before sign-in or after logout.exchangeCodeForToken, refreshAccessToken and setAccessToken store the value.ExampleBasic usage: check for a stored access tokenimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

const accessToken = oauthHandler.getAccessToken()
console.log(accessToken === undefined ? 'No access token' : 'Access token stored')
```

## getOauthAppAuthorization

getOauthAppAuthorization finds the authorization that the signed-in user gave the app and returns its UID.

This method takes no parameters.

```
Returns: Promise<string>. The authorization UID of the signed-in user.
ValidationThere is no client-side validation of the stored values.The returned promise rejects with an Error when the app has no authorizations, or none of them belongs to the stored user UID.The returned promise rejects with an Error when Developer Hub rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the response.Additional Resource: Refer to Content Management API Errors for the full error code list.
BehaviorSends GET /manifests/<appId>/authorizations to the Developer Hub host, with the stored access token as authorization: Bearer <token> and the stored organization UID as the organization_uid header.Reads the data array of the response, keeps the items whose user.uid matches the stored user UID, and resolves to the authorization_uid of the first one.Replaces the default headers of the client with authorization, organization_uid and Content-type: application/json. Later requests of the client send these headers.ExampleBasic usage: find the authorization of the signed-in userimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setOrganizationUID('<ORGANIZATION_UID>')
oauthHandler.setUserUID('<USER_UID>')

try {
  const authorizationId = await oauthHandler.getOauthAppAuthorization()
  console.log(authorizationId)
} catch (error) {
  // Developer Hub rejected the request, or the user has no authorization for the app
  console.error(error.status, error.errorCode, error.errorMessage || error.message)
}
```

## getOrganizationUID

getOrganizationUID returns the organization UID that the client stores from the token response.

This method takes no parameters.

```
Returns: string. The organization UID, or null.
ValidationThere is no client-side validation. getOrganizationUID never throws.BehaviorClient-side only. getOrganizationUID sends no request.Reads the value from the token storage of the client, which every handler of the client shares.Returns null when the client stores no organization UID.exchangeCodeForToken and setOrganizationUID store the value. getOauthAppAuthorization sends it as the organization_uid header.ExampleBasic usage: read the organization of the signed-in userimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

const organizationUid = oauthHandler.getOrganizationUID()
console.log(organizationUid)
```

## getRefreshToken

getRefreshToken returns the refresh token that the client stores.

This method takes no parameters.

```
Returns: string. The refresh token, or null.
ValidationThere is no client-side validation. getRefreshToken never throws.BehaviorClient-side only. getRefreshToken sends no request.Reads the value from the token storage of the client, which every handler of the client shares.Returns null when the client stores no refresh token.exchangeCodeForToken, refreshAccessToken and setRefreshToken store the value. Save it to restore the session later with setRefreshToken.ExampleBasic usage: read the refresh token to save itimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

const refreshToken = oauthHandler.getRefreshToken()
console.log(refreshToken)
```

## getTokenExpiryTime

getTokenExpiryTime returns the time at which the SDK treats the stored access token as expired.

This method takes no parameters.

```
Returns: number. The expiry time in milliseconds, or null.
ValidationThere is no client-side validation. getTokenExpiryTime never throws.BehaviorClient-side only. getTokenExpiryTime sends no request.Reads the value from the token storage of the client, which every handler of the client shares.Returns null when the client stores no expiry time.The value is a timestamp in milliseconds, like Date.now(). After a token request, it is the time of the response plus expires_in minus 60 seconds. Refresh the token with refreshAccessToken before this time passes.ExampleBasic usage: print the remaining lifetime of the access tokenimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

const expiryTime = oauthHandler.getTokenExpiryTime()
if (expiryTime !== null) {
  console.log('Seconds left:', Math.round((expiryTime - Date.now()) / 1000))
}
```

## getUserUID

getUserUID returns the user UID that the client stores from the token response.

This method takes no parameters.

```
Returns: string. The user UID, or null.
ValidationThere is no client-side validation. getUserUID never throws.BehaviorClient-side only. getUserUID sends no request.Reads the value from the token storage of the client, which every handler of the client shares.Returns null when the client stores no user UID.exchangeCodeForToken and setUserUID store the value. getOauthAppAuthorization uses it to find the authorization of the user.ExampleBasic usage: read the UID of the signed-in userimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

const userUid = oauthHandler.getUserUID()
console.log(userUid)
```

## handleRedirect

handleRedirect reads the authorization code from the redirect URL and exchanges it for tokens.

```
Returns: Promise<void>. This method resolves to nothing.
ValidationThe returned promise rejects with TypeError when url is not an absolute URL, because handleRedirect parses it with the URL class.The returned promise rejects with an Error when the URL has no code query parameter. handleRedirect sends no request in that case.The returned promise rejects with an Error when Developer Hub rejects the exchange. The error carries status and statusText, and error, errorMessage and errorCode from the response body.Additional Resource: Refer to Content Management API Errors for the full error code list.
BehaviorCalls exchangeCodeForToken with the code value of the URL. The tokens land on the client as they do for that method.Resolves to undefined. Read the tokens with getAccessToken and the other getters.handleRedirect replaces the default headers of the client, as exchangeCodeForToken does. The OAuthHandler page describes the effect and the workaround.ExampleBasic usage: exchange the authorization code from the redirect URLimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

console.log('Open this URL and sign in:', await oauthHandler.authorize())
// Pass the full URL that the browser was redirected to: node redirect.mjs "<url>"
const redirectUrl = process.argv[2]

try {
  const savedHeaders = client.axiosInstance.defaults.headers
  await oauthHandler.handleRedirect(redirectUrl)
  client.axiosInstance.defaults.headers = savedHeaders
  console.log(oauthHandler.getUserUID(), oauthHandler.getOrganizationUID())
} catch (error) {
  // Thrown for a URL without a code, or when Developer Hub rejects the exchange
  console.error(error.status, error.error, error.message)
}
```

Full redirect URL, with the code query parameter.

## logout

logout revokes the app authorization of the signed-in user and clears the tokens that the client stores.

This method takes no parameters.

```
Returns: Promise<string>. The text Logged out successfully.
Warning: logout revokes the authorization that the user gave the app. The user must sign in and approve the app again, and you cannot undo it.
ValidationThere is no client-side validation.The returned promise rejects with an Error when the client stores no authorization for the stored user UID, because getOauthAppAuthorization finds nothing to revoke.The returned promise rejects with an Error when Developer Hub rejects a request. The error carries status, statusText, errorMessage, errorCode and errors from the response.Additional Resource: Refer to Content Management API Errors for the full error code list.
BehaviorCalls getOauthAppAuthorization to find the authorization UID of the stored user, then revokeOauthAppAuthorization with it. That is two requests to the Developer Hub host.After both requests succeed, clears every value that the handler stored on the client: tokens, UIDs, expiry time, app ID, client ID and redirect URI.The default headers of the client keep the revoked authorization header and the organization_uid header, so later requests of the client still send them. Create a new client to sign in again.logout does not end an authtoken session. Use the logout method of the client for that.ExampleBasic usage: sign the user outimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setOrganizationUID('<ORGANIZATION_UID>')
oauthHandler.setUserUID('<USER_UID>')

try {
  const message = await oauthHandler.logout()
  console.log(message, oauthHandler.getAccessToken())
} catch (error) {
  // A request failed, or the user has no authorization for the app
  console.error(error.status, error.errorCode, error.errorMessage || error.message)
}
```

## refreshAccessToken

refreshAccessToken gets a new access token with a refresh token and stores it on the client.

```
Returns: Promise<OAuthResponse>. The token response with the new access token.
ValidationThe returned promise rejects with an Error when you pass no refresh token and the client stores none, because the token request needs one. refreshAccessToken sends no request in that case.The returned promise rejects with an Error when Developer Hub rejects the request. The error carries status and statusText, and error, errorMessage and errorCode from the response body.Additional Resource: Refer to Content Management API Errors for the full error code list.
BehaviorSends POST /token to the Developer Hub host of the client with a form body: grant_type=refresh_token, refresh_token, and the client_id and redirect_uri that the client stores.On success, stores the new access_token and expiry time. It stores the new refresh_token when the response has one, else it keeps the old one. It does not change the stored organization UID or user UID.Resolves to the response body as it is.When the stored access token has already expired, the request does not complete. Call setTokenExpiryTime with a time in the future first, as the second example below shows.refreshAccessToken replaces the default headers of the client. The OAuthHandler page describes the effect and the workaround.ExampleBasic usage: refresh the token before it expiresimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setRefreshToken('<REFRESH_TOKEN>')
oauthHandler.setTokenExpiryTime(Date.now() + 60000)

try {
  const savedHeaders = client.axiosInstance.defaults.headers
  const tokens = await oauthHandler.refreshAccessToken()
  client.axiosInstance.defaults.headers = savedHeaders
  console.log(tokens.expires_in, oauthHandler.getTokenExpiryTime())
} catch (error) {
  // Developer Hub rejected the request. The error carries status, error and errorMessage.
  console.error(error.status, error.error, error.errorMessage)
}All parameters: refresh after the stored token expired, with a saved refresh tokenimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  if (oauthHandler.getTokenExpiryTime() !== null && Date.now() > oauthHandler.getTokenExpiryTime()) {
    // Move the expiry time forward so the token request itself can start
    oauthHandler.setTokenExpiryTime(Date.now() + 60000)
  }
  const savedHeaders = client.axiosInstance.defaults.headers
  const tokens = await oauthHandler.refreshAccessToken('<REFRESH_TOKEN>')
  client.axiosInstance.defaults.headers = savedHeaders
  console.log(tokens.access_token !== undefined)
} catch (error) {
  console.error(error.message)
}
```

Refresh token to send instead of the stored one.

## revokeOauthAppAuthorization

revokeOauthAppAuthorization revokes one authorization of the app, so its tokens stop working.

```
Returns: Promise<any>. The API response of the revoke request.
Warning: You cannot restore a revoked authorization. The user must sign in and approve the app again.
ValidationrevokeOauthAppAuthorization checks only the length of authorizationId. With undefined, an empty string or a one-character value, it sends no request and resolves to undefined.The returned promise rejects with an Error when Developer Hub rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the response.Additional Resource: Refer to Content Management API Errors for the full error code list.
BehaviorSends DELETE /manifests/<appId>/authorizations/<authorizationId> to the Developer Hub host, with the stored access token as authorization: Bearer <token> and the stored organization UID as the organization_uid header.Resolves to the response body as it is.Does not clear the tokens that the client stores. logout revokes the authorization of the signed-in user and clears them.Replaces the default headers of the client with authorization, organization_uid and Content-type: application/json.ExampleBasic usage: revoke the authorization of the signed-in userimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setOrganizationUID('<ORGANIZATION_UID>')

try {
  const response = await oauthHandler.revokeOauthAppAuthorization('<AUTHORIZATION_ID>')
  console.log(response)
} catch (error) {
  // Developer Hub rejected the request. The error carries status, errorCode and errorMessage.
  console.error(error.status, error.errorCode, error.errorMessage)
}
```

UID of the authorization to revoke.

## setAccessToken

setAccessToken stores an access token that you saved earlier, so the client sends it without a new sign-in.

```
Returns: void. This method returns nothing.
ValidationThrows Error if token is falsy, for example undefined, null, an empty string or 0, because the client needs an access token to store. The stored value stays unchanged.setAccessToken does not check the format of the value.BehaviorClient-side only. setAccessToken sends no request.Writes the value to the token storage of the client, which every handler of the client shares.Every later request of the client that carries no authtoken or authorization header sends the token as authorization: Bearer <token>.ExampleBasic usage: restore a saved sessionimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  oauthHandler.setAccessToken('<ACCESS_TOKEN>')
  oauthHandler.setRefreshToken('<REFRESH_TOKEN>')
  oauthHandler.setTokenExpiryTime(Date.now() + 60 * 60 * 1000)
  console.log(oauthHandler.getAccessToken() !== undefined)
} catch (error) {
  // Thrown when the value is empty
  console.error(error.message)
}
```

Access token to store.

## setOrganizationUID

setOrganizationUID stores the organization UID that [getOauthAppAuthorization](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-getoauthappauthorization) and [revokeOauthAppAuthorization](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-revokeoauthappauthorization) send as the organization\_uid header.

```
Returns: void. This method returns nothing.
ValidationThrows Error if organizationUID is falsy, for example undefined, null, an empty string or 0, because the client needs an organization UID to store. The stored value stays unchanged.setOrganizationUID does not check the format of the value.BehaviorClient-side only. setOrganizationUID sends no request.Writes the value to the token storage of the client, which every handler of the client shares.Set it when you restore a saved session and plan to call logout.ExampleBasic usage: restore the organization of a saved sessionimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  oauthHandler.setOrganizationUID('<ORGANIZATION_UID>')
  console.log(oauthHandler.getOrganizationUID())
} catch (error) {
  // Thrown when the value is empty
  console.error(error.message)
}
```

Organization UID to store.

## setRefreshToken

setRefreshToken stores a refresh token, which [refreshAccessToken](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-refreshaccesstoken) sends when you pass none.

```
Returns: void. This method returns nothing.
ValidationThrows Error if token is falsy, for example undefined, null, an empty string or 0, because the client needs a refresh token to store. The stored value stays unchanged.setRefreshToken does not check the format of the value.BehaviorClient-side only. setRefreshToken sends no request.Writes the value to the token storage of the client, which every handler of the client shares.refreshAccessToken reads the stored value when you call it without an argument.ExampleBasic usage: store a saved refresh token before refreshingimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  oauthHandler.setRefreshToken('<REFRESH_TOKEN>')
  console.log(oauthHandler.getRefreshToken())
} catch (error) {
  // Thrown when the value is empty
  console.error(error.message)
}
```

Refresh token to store.

## setTokenExpiryTime

setTokenExpiryTime stores the time at which the SDK treats the stored access token as expired.

```
Returns: void. This method returns nothing.
ValidationThrows Error if expiryTime is falsy, for example undefined, null, an empty string or 0, because the client needs an expiry time to store. The stored value stays unchanged.setTokenExpiryTime does not check the format of the value.BehaviorClient-side only. setTokenExpiryTime sends no request.Writes the value to the token storage of the client, which every handler of the client shares.Before each request, the SDK compares the stored value with Date.now(). Pass a timestamp in milliseconds. A Date object also compares correctly, but getTokenExpiryTime then returns the Date.ExampleBasic usage: store the expiry time of a saved sessionimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  // The saved token stays valid for one more hour
  oauthHandler.setTokenExpiryTime(Date.now() + 60 * 60 * 1000)
  console.log(new Date(oauthHandler.getTokenExpiryTime()).toISOString())
} catch (error) {
  // Thrown when the value is empty
  console.error(error.message)
}
```

Expiry timestamp in milliseconds, like Date.now().

## setUserUID

setUserUID stores the user UID that [getOauthAppAuthorization](/docs/developers/sdks/content-management-sdk/javascript/reference/oauthhandler#oauthhandler-getoauthappauthorization) uses to find the authorization of the user.

```
Returns: void. This method returns nothing.
ValidationThrows Error if userUID is falsy, for example undefined, null, an empty string or 0, because the client needs a user UID to store. The stored value stays unchanged.setUserUID does not check the format of the value.BehaviorClient-side only. setUserUID sends no request.Writes the value to the token storage of the client, which every handler of the client shares.Set it when you restore a saved session and plan to call logout.ExampleBasic usage: restore the user of a saved sessionimport contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  oauthHandler.setUserUID('<USER_UID>')
  console.log(oauthHandler.getUserUID())
} catch (error) {
  // Thrown when the value is empty
  console.error(error.message)
}
```

User UID to store.

## OAuthHandler | JavaScript Management SDK | Contentstack

The OAuthHandler class in the JavaScript Management SDK runs the OAuth sign-in: it builds the authorization URL, exchanges the authorization code for tokens, refreshes them and signs out.