Skip to main content

@parcely/auth-redirect

Redirect the browser to a login URL on 401/403.

import { createAuthRedirect } from '@parcely/auth-redirect'

createAuthRedirect(options)

Creates a redirect handler that can be installed on a client.

Options

OptionTypeDefaultDescription
loginUrlstring | ((err: HttpError) => string)(required)The URL to redirect to. Can be a function for dynamic URLs.
onnumber[][401, 403]HTTP status codes that trigger a redirect.
preserveReturnTobooleantrueWhether to append the current path as a query parameter.
returnToParamstring'return_to'The name of the return-to query parameter.
shouldRedirect(err: HttpError) => booleanundefinedOptional predicate. Return false to skip the redirect for certain requests.
cooldownMsnumber2000Debounce period in milliseconds to prevent redirect storms from multiple concurrent 401s.

Return value

{
response: InterceptorHandler<HttpResponse<unknown>>
install(client: Client): void
}
PropertyDescription
responseA response interceptor handler that triggers the redirect.
install(client)Convenience method that wires the response interceptor onto the client.

Browser-only

This addon uses window.location.href to redirect. In non-browser environments (Node, Bun, Deno), the interceptor is a no-op and emits a one-shot console.warn.

Example

import { createClient } from '@parcely/core'
import { createAuthRedirect } from '@parcely/auth-redirect'

const http = createClient({ baseURL: 'https://api.example.com' })

const redirect = createAuthRedirect({
loginUrl: '/login',
on: [401, 403],
preserveReturnTo: true,
returnToParam: 'return_to',
shouldRedirect: (err) => !err.config.url?.includes('/public/'),
cooldownMs: 2000,
})

redirect.install(http)

Combining with @parcely/auth-token

Install auth-token first, then auth-redirect. The redirect fires only after the token refresh has failed:

import { createAuthToken } from '@parcely/auth-token'
import { createAuthRedirect } from '@parcely/auth-redirect'

auth.install(http) // first: tries to refresh the token
redirect.install(http) // second: redirects if refresh failed

See also