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:
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:
baseUrlmust be an absolute URL. End it with/, so thatauthFetch("orders")lands under it rather than beside it.authFetchalso takes aURLor aRequest, so an HTTP client with afetchoption can send its requests through it. See Other HTTP clients.- While the user is signed in,
authFetchsetsAuthorization: Bearer …. It replaces anyAuthorizationheader the request already has. - A
Requestwith a body can be sent only one time, as withfetch. 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,
authFetchuses 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
signOutOnRepeated401tofalse, as below. - Without a refresh token or a
refreshoption, there's nothing to refresh with, so the first 401 signs the user out, whateversignOutOnRepeated401is. - If your backend rejects the refresh token, the user is signed out, and
authFetchresolves the original 401. If the user signs out or switches account while the refresh runs, it rejects withSESSION_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:
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 URL | INVALID_OPTIONS. The token goes only to baseUrl's origin. |
The Request comes from a polyfill or another realm, such as an iframe | INVALID_OPTIONS |
| The user is signed out | UNAUTHENTICATED, unless optional is true |
| The session is locked | LOCKED, even when optional is true |
| The saved session can't be read | PERSISTENCE_FAILED |
| A refresh fails | That 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 runs | SESSION_CHANGED |
| The response is a redirect | A TypeError, as fetch gives when it refuses a redirect |
| The network fails | fetch'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:
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:
import { } from "@monarcode/session-kit/http";
import { } from "./auth.js";
import { } from "./backend.js";
export const = (, {
: `${}/`,
: false,
});Next steps
- Other HTTP clients: send ky, axios or
openapi-fetch requests through
authFetch, or add the token yourself. - Errors: show a failed refresh or an outage to the user.
createAuthFetchreference: every option and error.