Skip to content

Headers New ​

faxios exposes its own FaxiosHeaders class to manipulate headers using a Map-like API that guarantees case-insensitive keys. This class is used internally by faxios to manage headers, but it's also exposed to the user for convenience. Although HTTP headers are case-insensitive, faxios will retain the case of the original header for stylistic reasons and for a workaround when servers mistakenly consider the header's case. The old method of directly manipulating the headers object is still available, but deprecated and not recommended for future usage.

Working with headers ​

The FaxiosHeaders object instance can contain different types of internal values that control the setting and merging logic. The final headers object is obtained by faxios by calling the toJSON method. The FaxiosHeaders object is also iterable, so you can use it in loops or convert it to an array or object.

The header values can be one of the following types:

  • string - normal string value that will be sent to the server
  • null - skip header when converting to JSON
  • false - skip header when converting to JSON, additionally indicates that set method must be called with rewrite option set to true to overwrite this value (faxios uses this internally to allow users to opt out of installing certain headers like User-Agent or Content-Type)
  • undefined - value is not set

WARNING

The header value is considered set if it is not undefined.

Inside .use() middleware and transformers, the request headers are always a FaxiosHeaders instance, as in this example:

ts
import faxios from "@gcmdev/faxios";

const api = faxios.create().use(async (ctx, next) => {
  ctx.config.headers.set("My-header", "value");

  ctx.config.headers.set({
    "My-set-header1": "my-set-value1",
    "My-set-header2": "my-set-value2",
  });

  // Disable subsequent setting of this header by faxios
  ctx.config.headers.set("User-Agent", false);

  ctx.config.headers.setContentType("text/plain");

  return next(ctx);
});

await api.get("/api/data");

You can iterate over a FaxiosHeaders instance using any iterable method, like for-of loop, forEach, or spread operator:

js
import { FaxiosHeaders } from "@gcmdev/faxios";

const headers = new FaxiosHeaders({
  foo: '1',
  bar: '2',
  baz: '3',
});

for (const [header, value] of headers) {
  console.log(header, value);
}

// foo 1
// bar 2
// baz 3

Setting headers on a request ​

The most common place to set headers is the headers option in your request config or instance config:

js
import faxios from "@gcmdev/faxios";

const id = 42;

// On a single request
await faxios.get('/api/data', {
  headers: {
    Accept: 'application/json',
    'X-Request-Id': String(id),
  },
});

// On an instance (applied to every request)
const api = faxios.create({
  headers: {
    'X-App-Version': '2.0.0',
  },
});

faxios skips the header names __proto__, constructor and prototype (in any case) wherever headers are set, including FaxiosHeaders.from(), new FaxiosHeaders() and set(). A header map from JSON.parse with one of these keys keeps its other headers. Response headers whose names exist on Object.prototype, such as ToString or ValueOf, are kept like any other header.

Header typing ​

The headers option is typed as FaxiosConfigHeaders. Your editor suggests common header names and Content-Type values, and any other header name is still allowed. It accepts three shapes:

  • A header bag: { Accept: "application/json" }.
  • Method header groups: headers under common apply to every method, headers under a method name (get, post, ...) apply only to that method.
  • A FaxiosHeaders instance.

A bag and groups can be mixed in one object:

ts
import faxios from "@gcmdev/faxios";

const token = "my-token";

const api = faxios.create({
  headers: {
    "X-App-Version": "2.0.0",
    common: { Authorization: "Bearer " + token },
    post: { "Content-Type": "application/json" },
  },
});

await api.post("/api/data", { name: "faxios" });

Header values can be a string, an array of strings, a number, a boolean, null or undefined:

  • undefined drops a value inherited from the instance defaults, but faxios may still set its own value later (for example Content-Type for a JSON body).
  • null or false keeps the header off the request entirely.

Objects and functions are rejected by the type checker. Convert other values with String(...) first.

ts
import faxios from "@gcmdev/faxios";

const api = faxios.create({ headers: { common: { Authorization: "Bearer my-token" } } });

// Send this one request without the inherited Authorization header
await api.get("/public", { headers: { Authorization: null } });

The types FaxiosConfigHeaders, RawFaxiosRequestHeaders (the header bag) and HeadersDefaults (the method groups) are exported from @gcmdev/faxios.

Preserving a specific header case ​

faxios header names are case-insensitive, but FaxiosHeaders keeps the case of the first matching key it sees. If you need a specific case for a server with non-standard case-sensitive behavior, define a case preset in defaults and then set values as usual.

js
import faxios from "@gcmdev/faxios";

const url = '/upload';
const data = new Uint8Array([1, 2, 3]);

const api = faxios.create();

api.defaults.headers.common = {
  'content-type': undefined,
  accept: undefined,
};

await api.put(url, data, {
  headers: {
    'Content-Type': 'application/octet-stream',
    Accept: 'application/json',
  },
});

You can also do this with FaxiosHeaders directly when composing headers:

js
import faxios, { FaxiosHeaders } from "@gcmdev/faxios";

const url = '/upload';
const data = new Uint8Array([1, 2, 3]);

const headers = FaxiosHeaders.concat(
  { 'content-type': undefined },
  { 'Content-Type': 'application/octet-stream' }
);

await faxios.put(url, data, { headers });

Setting headers in middleware ​

Middleware is the right place to attach dynamic headers like auth tokens, because the token may not be available when the instance is first created. For bearer tokens, the built-in authBearer plugin does this for you.

js
import faxios from "@gcmdev/faxios";

const getAuthToken = () => 'my-token'; // e.g. read from your auth store

const api = faxios.create().use(async (ctx, next) => {
  const token = getAuthToken(); // read at request time
  ctx.config.headers.set('Authorization', `Bearer ${token}`);
  return next(ctx);
});

await api.get('/api/data');

Keep and use the value use() returns; see Middleware.

Unicode header values ​

FaxiosHeaders preserves non-control Unicode characters in header values so middleware can transform them before the request is sent. CR/LF and other C0 control bytes are still stripped at set time to prevent header injection.

The adapter sanitizes header values to byte-safe (HT, printable ASCII, and Latin-1 supplement) right before handing them to fetch's Headers. If a header value contains characters outside that range and you have not encoded it, those characters are stripped, which can produce an empty value on the wire.

If you need to send non-ASCII data in a header, encode it in middleware:

js
import faxios from "@gcmdev/faxios";

const api = faxios.create().use(async (ctx, next) => {
  if (ctx.config.headers.has('X-Name')) {
    ctx.config.headers.set('X-Name', encodeURIComponent(String(ctx.config.headers.get('X-Name'))));
  }
  return next(ctx);
});

await api.get('/api/data', {
  headers: {
    'X-Name': '请求用户',
  },
});
// → request is sent with X-Name: %E8%AF%B7%E6%B1%82%E7%94%A8%E6%88%B7

Reading response headers ​

Response headers are available on response.headers as a FaxiosHeaders instance, and are typed as FaxiosHeaders, so every method below works in TypeScript without a cast. All header names are lower-cased:

js
import faxios from "@gcmdev/faxios";

const response = await faxios.get('/api/data');

console.log(response.headers['content-type']);
// application/json; charset=utf-8

console.log(response.headers.get('x-request-id'));
// abc123

console.log(response.headers.has('x-request-id'));
// true

console.log(response.headers.getContentType(/charset=([^;]+)/)?.[1]);
// utf-8

for (const cookie of response.headers.getSetCookie()) {
  console.log(cookie); // one entry per Set-Cookie header
}

for (const [ name, value ] of response.headers) {
  console.log(name, value);
}

Removing a default header ​

To opt out of a header that faxios sets by default (such as Content-Type or User-Agent), set its value to false:

js
import faxios from "@gcmdev/faxios";

const payload = new FormData();
payload.append('name', 'faxios');

await faxios.post('/api/data', payload, {
  headers: {
    'Content-Type': false, // let the browser set it automatically (e.g. for FormData)
  },
});

For more detail on the full FaxiosHeaders method API, see the Header methods page.

faxios is provided under the MIT license. Based on axios by Matt Zabriskie and collaborators.