Skip to Content
Plugins

Refresh a token

Renew an expired access token with the bearer plugin and send the request again.

Access tokens expire, often in the middle of a session, and a call made with an expired one gets a 401. Rather than fail that call, bearer can get a new token and send the request again. This page shows how to set that up, and how refreshing behaves when several calls are refused at the same time.

Add a refresh function

When a request that bearer sent a token with gets a 401, bearer asks refresh for a new token, then sends the request again with it. Pass refresh next to token:

import {  } from "@monarcode/effetch";
import {  } from "@monarcode/effetch/plugins";

declare const : {
  readonly : () => string | undefined;
  readonly : () => <string | undefined>;
};

export class  extends .<>()("Api", {
  : "https://api.example.com",
  : [
    ({ : () => .(), : () => .() }),
  ],
}) {}

refresh gets the refused request, as it was sent, with its Authorization header. Like token, it can be a function, sync or async, or an Effect, whose error and services become the client's.

bearer uses the new token for that request only. Have refresh store it where token reads it, so later requests send it too.

Make the refresh call skip bearer

When refresh is a function that runs your client to get the new token, the refresh call must skip bearer with plugins: { bearer: false }. bearer can't tell that call apart from any other, so without it, a 401 to the refresh call would wait for the refresh it's part of, and never end:

import * as  from "effect/Effect";
import * as  from "effect/http/FetchHttpClient";
import * as  from "effect/Layer";
import * as  from "effect/ManagedRuntime";
import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";
import {  } from "@monarcode/effetch/plugins";

declare const : {
  readonly : () => string | undefined;
  readonly : () => string | undefined;
  readonly : (: string) => void;
};

const  = .({ : . });

export class  extends .<>()("Api", {
  : "https://api.example.com",
  : [({ : () => .(), : () => () })],
}) {}

const  = .(
  ..(.(.)),
);

function (): <string | undefined> {
  return .(
    .(function* () {
      const  = yield* ;
      const {  } = yield* .("/auth/refresh", {
        : { : .() },
        : ,
        : { : false },
      });
      .();
      return ;
    }).(.(() => )),
  );
}

When the refresh call fails, such as when the refresh token has expired too, renew gives undefined, so the original call ends with its 401. A promise that rejects would make the call die instead.

An Effect refresh can't hang this way: calls made inside it never refresh. Skipping bearer there still keeps the expired token off the refresh call.

How refreshing behaves

Refreshing follows these rules when calls are refused, fail or are sent again:

What's next

On this page