Skip to main content

Browser

Official

Vanilla JavaScript SDK for browser apps without a framework.

Accessing Protected APIs

~3 min

When building applications with ThunderID, you often need to call protected APIs that require authentication. The Browser SDK provides built-in methods for making authenticated HTTP requests with automatic token management.

Accessing Protected APIs

1

Using the Built-In HTTP Client

The `ThunderIDBrowserClient` provides `httpRequest()` and `httpRequestAll()` methods that automatically attach the access token as a Bearer token to outgoing requests. ### Basic API Request

src/api.js
js

async function fetchUserData(userId) {
  const response = await auth.httpRequest({
    url: `https://localhost:8090/users/${userId}`,
    method: 'GET',
    headers: {
      Accept: 'application/json',
    },
  })

  return response.data
}
2

Using the Access Token Directly

If you prefer to use your own HTTP client (e.g., `fetch` or `axios`), retrieve the access token and attach it manually:

src/api.js
js

async function fetchWithToken(url) {
  const token = await auth.getAccessToken()

  const response = await fetch(url, {
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: 'application/json',
    },
  })

  return response.json()
}
3

Error Handling

Handle API errors by catching exceptions from `httpRequest()`:

src/api.js
js

async function fetchData() {
  try {
    const response = await auth.httpRequest({
      url: 'https://localhost:8090/users',
      method: 'GET',
    })

    return response.data
  } catch (error) {
    if (error.response?.status === 401) {
      // Token expired or invalid — trigger re-authentication
      await auth.signIn()
    } else {
      console.error('API error:', error.message)
    }
  }
}
ThunderID LogoThunderID Logo

Product

DocsAPIsSDKs
© Copyright Linux Foundation Europe.For web site terms of use, trademark policy and other project policies please see https://linuxfoundation.eu/en/policies.