Auth: Bearer, Basic, and custom headers
Use case
Attach authentication credentials to every request. You can do this manually with default headers, with a request interceptor, or with the @parcely/auth-token addon.
Manual header
import { createClient } from '@parcely/core'
const http = createClient({
baseURL: 'https://api.example.com',
headers: {
Authorization: 'Bearer my-access-token',
},
})
Request interceptor
For dynamic tokens (e.g., read from storage on each request):
import { createClient } from '@parcely/core'
const http = createClient({ baseURL: 'https://api.example.com' })
http.interceptors.request.use((config) => ({
...config,
headers: {
...config.headers,
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
}))
Using @parcely/auth-token
The @parcely/auth-token addon provides a higher-level API:
import { createClient } from '@parcely/core'
import { createAuthToken } from '@parcely/auth-token'
const http = createClient({ baseURL: 'https://api.example.com' })
const auth = createAuthToken({
scheme: 'Bearer',
getToken: async () => localStorage.getItem('access_token'),
})
auth.install(http)
Basic auth
const auth = createAuthToken({
scheme: 'Basic',
getToken: async () => btoa(`${username}:${password}`),
})
auth.install(http)
Custom header
const auth = createAuthToken({
scheme: 'Token',
header: 'X-API-Key',
getToken: async () => apiKey,
})
auth.install(http)
Axios equivalent
In axios you would typically use an interceptor or the auth config option:
// axios auth config:
await http.get('/data', { auth: { username: 'user', password: 'pass' } })
// parcely equivalent (manual):
const encoded = btoa('user:pass')
await http.get('/data', { headers: { Authorization: `Basic ${encoded}` } })
parcely does not have a dedicated auth config key. Use headers directly or the @parcely/auth-token addon.
Notes and gotchas
- The
Authorizationheader is in the defaultsensitiveHeaderslist, so it is automatically stripped on cross-origin redirects. - The
Authorizationheader value is redacted in error objects and the response envelopeconfig. @parcely/auth-tokensupports customheadernames (e.g.,X-API-Key) and customschemestrings.