Skip to main content

Redirect to login on 401/403 in the browser

Use case

In a browser app, redirect the user to a login page when the API returns 401 or 403.

Using @parcely/auth-redirect

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',
})

redirect.install(http)

When the client receives a 401 or 403, the browser navigates to /login?return_to=%2Fcurrent-path.

Options

OptionTypeDefaultDescription
loginUrlstring | ((err) => string)(required)URL to redirect to. Can be a function for dynamic URLs.
onnumber[][401, 403]Status codes that trigger a redirect.
preserveReturnTobooleantrueAppend the current path as a query parameter.
returnToParamstring'return_to'Name of the return-to query parameter.
shouldRedirect(err) => booleanundefinedOptional predicate to skip redirect for certain requests.
cooldownMsnumber2000Debounce period to prevent redirect storms.

Conditional redirect

Skip the redirect for certain routes:

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

Combining with @parcely/auth-token

If you install both addons, install auth-token first. The redirect will only fire after the token refresh has failed:

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

Notes and gotchas

  • Browser-only. In non-browser runtimes (Node, Bun, Deno), the interceptor is a no-op and emits a one-shot console.warn.
  • The cooldownMs option prevents multiple rapid 401s from triggering multiple redirects.
  • The redirect uses window.location.href assignment, not history.pushState.