Skip to Content
Using the client

Authenticated requests

Call your API with the access token, get a new one after a 401, and keep the token away from every other server.

Your API wants the access token on every request, and it answers 401 when the token has expired or been revoked. createAuthFetch gives you a fetch that adds the token, gets a new one after a 401, and sends the token only to your API, so your request code doesn't have to.

This page shows how to send requests with it, what happens after a 401, and when it rejects. It builds on the authFetch from Getting started.

Send a request

authFetch takes the same arguments as fetch. Pass a path, and it's resolved against baseUrl, the way a link is resolved against a page's address:

src/orders.ts
import {  } from "./api.js";

export async function (: number) {
  // https://dummyjson.com/auth/carts/user/1, with the access token.
  const  = await (`auth/carts/user/${}`);
  if (!.) throw new (`Orders failed (${.})`);
  return .();
}

Here's what to know about the URL and the headers:

  • baseUrl must be an absolute URL. End it with /, so that authFetch("orders") lands under it rather than beside it.
  • authFetch also takes a URL or a Request, so an HTTP client with a fetch option can send its requests through it. See Other HTTP clients.
  • While the user is signed in, authFetch sets Authorization: Bearer …. It replaces any Authorization header the request already has.
  • A Request with a body can be sent only one time, as with fetch. To send a write again, keep a clone.

After a 401

When your API answers 401, authFetch gets a new access token and sends the request again. It does that only for GET and HEAD, which are safe to send twice. A POST or any other method comes back with its 401, for you to decide.

The rest of the 401 handling:

  • Requests that get a 401 at the same time share one refresh. If another request or another tab has already replaced the token, authFetch uses the new one without a refresh.
  • If the request sent again gets a 401 too, your API has rejected the new token as well, so the user is signed out. If your API also answers 401 for other reasons, set signOutOnRepeated401 to false, as below.
  • Without a refresh token or a refresh option, there's nothing to refresh with, so the first 401 signs the user out, whatever signOutOnRepeated401 is.
  • If your backend rejects the refresh token, the user is signed out, and authFetch resolves the original 401. If the user signs out or switches account while the refresh runs, it rejects with SESSION_CHANGED.

Retry a write

Because authFetch never sends a write twice, retry it yourself where sending it twice is safe. After the 401, the token has already been refreshed:

src/add-to-cart.ts
import {  } from "./api.js";

export async function (: number, : number) {
  const  = () =>
    ("auth/carts/add", {
      : "POST",
      : { "Content-Type": "application/json" },
      : .({
        ,
        : [{ : , : 1 }],
      }),
    });

  let  = await ();
  // The 401 refreshed the token, so one more try uses the new one.
  if (. === 401)  = await ();
  if (!.) throw new (`Add to cart failed (${.})`);
}

When it rejects

authFetch rejects rather than send the token somewhere it shouldn't go, or resolve a response meant for another account. Here's when it rejects, and with what:

When…authFetch rejects with…
The URL is on another origin, has a username or password in it, or isn't a valid URLINVALID_OPTIONS. The token goes only to baseUrl's origin.
The Request comes from a polyfill or another realm, such as an iframeINVALID_OPTIONS
The user is signed outUNAUTHENTICATED, unless optional is true
The session is lockedLOCKED, even when optional is true
The saved session can't be readPERSISTENCE_FAILED
A refresh failsThat failure, such as REFRESH_FAILED, until a retry, a refresh, new tokens from another tab, or a sign-in or sign-out
The user signs out or switches account while the request runsSESSION_CHANGED
The response is a redirectA TypeError, as fetch gives when it refuses a redirect
The network failsfetch's own error, usually a TypeError

The last two aren't AuthErrors, so code that matches on code doesn't catch them. To show these failures, see Errors.

A redirect isn't followed, so the token never reaches a server your API redirects to. On React Native before Expo SDK 58, fetch follows a redirect whatever it's told. authFetch still refuses the response, but the redirected request has already gone out. Don't let your API redirect requests that carry a token.

Send requests while signed out

Some apps call one API for public and private endpoints alike. With optional: true, a signed-out request goes out without a token instead of rejecting:

src/public-api.ts
import {  } from "@monarcode/session-kit/http";

import {  } from "./auth.js";
import {  } from "./backend.js";

export const  = (, {
  : `${}/`,
  : true,
});

A request sent without a token keeps its own Authorization header, if it has one. A 401 to it comes back as it is, with no refresh and no sign-out.

Keep users signed in after a second 401

Some APIs answer 401 for reasons other than a rejected token, such as a resource the user can't see. With signOutOnRepeated401: false, a second 401 to the same request comes back as it is, and the user stays signed in:

src/reports-api.ts
import {  } from "@monarcode/session-kit/http";

import {  } from "./auth.js";
import {  } from "./backend.js";

export const  = (, {
  : `${}/`,
  : false,
});

Next steps

On this page