Skip to content

Advanced Techniques with @briklab/reqor ​

Once you’re comfortable with the basics, these patterns help you tailor reqor to complex applications.

Custom middleware ​

Middlewares can modify requests, short‑circuit responses, or implement retries yourself.

ts
import reqor from "@briklab/reqor";

function authMiddleware(token: string) {
  return {
    before: (context) => {
      context.init.headers = { ...(context.init.headers || {}), Authorization: `Bearer ${token}` };
    }
  };
}

reqor.use(authMiddleware("secret-token"));

// all subsequent requests include auth header
await reqor("/private").get();

Local middleware can be used for a single request. You can also short‑circuit and return a mocked response:

ts
await reqor("/cache")
  .use({
    before: (context) => {
      // modify request if needed
    },
    after: (response, context) => {
      if (cache.has(context.url)) {
        return cache.get(context.url); // skip network entirely
      }
      cache.set(context.url, response);
      return response;
    }
  })
  .get();

Global configuration ​

reqor exposes static helpers for setting default headers or global retry logic:

ts
reqor.headers().set("X-App","myapp");
reqor.use({
  before: (context) => {
    console.log("requesting", context.url);
  }
});

Clearing and resetting ​

ts
reqor.clearMiddlewares();
reqor.headers().clear();

Error handling ​

If a fetch fails after all retries the promise rejects with the Response object. Use try/catch or attach .catch().

ts
try {
  await reqor("/bad").retry(2).get();
} catch (err) {
  console.error("request failed", err);
}

You can also inspect err.status/err.body to make decisions.

Using fetchLater ​

Reqor supports fetchLater to obtain a ResponseLater and resolve manually.

ts
import { fetchLater } from "@briklab/reqor";

const later = await reqor("/slow").get({ later: true });
// do other work...
const res = await later.resolve();
console.log(res.status);

Tips and gotchas ​

  • Calling the same fluent method twice overwrites the previous value.
  • Options passed to get()/post() take precedence over fluent setters.
  • Middleware order is: global first, then local, then options-provided.

Live Demo ​

Additional resources ​