Choose which cookies you allow. You can change your choice at any time from “Cookie preferences”, at the bottom of every page. Learn more in the Privacy Policy.

Open-source library · npm

Neysla

Our brand's product · 2018 – 2026

About the project

Neysla was born in 2018 out of a concrete annoyance: on every project I kept rewriting the same nested API URLs, with their fixed parts and their identifiers. The idea was to model each resource once and, on each request, pass only what changes.

Version 4 is a complete rewrite in TypeScript on top of the native Fetch API: no runtime dependencies, types included, and distributed as ESM, CommonJS and a CDN bundle. It works the same in the browser and in Node.js 18+.

It is not an isolated experiment: Academia Luz de Luna, Onca Vega Press, the wedding invitation and the birthday gift on this same list all talk to their APIs through Neysla.

Technologies

  • TypeScript
  • Fetch API
  • Rollup
  • Vitest

Highlights

  • Two modes: direct requests or resources modeled once and reused.
  • Zero runtime dependencies; TypeScript types included.
  • ESM, CommonJS and an IIFE bundle for CDNs.
  • JSON, multipart and urlencoded bodies; upload progress in the browser.
  • Tests with Vitest, coverage on Codecov and continuous integration on GitHub Actions.

Documentation

Everything you need to use it, with code examples: move between sections from the index.

Installing Neysla

Install Neysla from npm or a CDN, learn its distribution formats (ESM, CJS, IIFE) and start consuming RESTful APIs in the browser or in Node.js 18+.

Neysla is an isomorphic, promise-based TypeScript library for consuming RESTful HTTP APIs from the browser or from Node.js 18+. You can use it in two ways:

  • Direct usage: one-off HTTP requests to a URL (Neysla.get, Neysla.post, and so on).
  • Modeler usage: define your API’s resources once (their static and dynamic parts) and reuse them across your whole application.

It has no runtime dependencies: it uses the native Fetch API and, only to report upload progress in the browser, XMLHttpRequest.

Install from npm

npm install neysla

Neysla ships named exports and its own type declarations, so there is no separate @types package:

import { Neysla } from "neysla";
import type { NeyslaResponse } from "neysla";

With CommonJS:

const { Neysla } = require("neysla");

Load from a CDN

To use it straight in the browser, load the minified bundle. The script exposes { Neysla, NeyslaModel } on window.Neysla:

<script src="https://cdn.jsdelivr.net/npm/neysla@4/dist/cdn/neysla.min.js"></script>
<script>
  const { Neysla } = window.Neysla;
</script>

Distribution formats

FormatFileUse it when…
ESMdist/esm/index.jsYou use a modern bundler or native ES modules (recommended).
CJSdist/cjs/index.cjsYour Node.js environment uses require().
IIFE / CDNdist/cdn/neysla.min.jsYou load the library with a <script> tag.
Typesdist/types/index.d.tsAlways: TypeScript picks them up automatically.

Requirements

  • Modern browsers with Fetch API support.
  • Node.js 18 or later (the version where fetch is global).

License and versioning

Neysla is released under the MIT license and follows semantic versioning. The code lives on GitHub and the package on npm.

If you are coming from version 3, check the migration section of the README: errors are now thrown as TypeError (instead of returning false) and response header names always arrive in lowercase.

Neysla direct usage

Make direct HTTP requests with Neysla (GET, HEAD, POST, PATCH, PUT and DELETE), send JSON, multipart or urlencoded bodies and handle responses and errors.

Direct usage is for one-off requests: you give Neysla the full URL and it takes care of sending the request, encoding the body and reading the response. Every method is static and returns a Promise.

MethodHTTP verbSends a body
Neysla.get(options)GETNo
Neysla.head(options)HEADNo
Neysla.post(options)POSTYes
Neysla.patch(options)PATCHYes
Neysla.put(options)PUTYes
Neysla.remove(options)DELETEYes

Request options

OptionTypeRequiredDefaultDescription
urlstringYes—Full endpoint URL.
paramsRecord<string, string | number | boolean | Array<string | number>>No—Query string parameters. An array repeats the key (?tag=a&tag=b).
headersRecord<string, string>No{}Request headers.
bodyRecord<string, unknown> | FormDataNo—Request body (only for post, patch, put and remove).
requestType"json" | "multipart" | "urlencoded"No"urlencoded"How the body is encoded and which Content-Type is sent.
responseType"json" | "text" | "arraybuffer" | "blob" | "document" | "stream"No"json"How the response body is read.
credentialsRequestCredentialsNo—Same as in fetch ("include" to send cookies cross-origin).
progress(event: ProgressEvent) => voidNo—Transfer progress; browser only (see below).

GET and HEAD

import { Neysla } from "neysla";

const response = await Neysla.get({
  url: "https://www.my-domain.com/api/users",
  params: { order: "age", tag: ["admin", "editor"] },
});
// GET https://www.my-domain.com/api/users?order=age&tag=admin&tag=editor
console.log(response.status, response.data);

const { headers } = await Neysla.head({
  url: "https://www.my-domain.com/api/users",
});

To download a file, read the response as a blob:

const { data: file } = await Neysla.get({
  url: "https://www.my-domain.com/api/reports/2026.pdf",
  responseType: "blob",
});

POST, PATCH, PUT and DELETE

The body is encoded according to requestType:

  • "json": JSON.stringify and Content-Type: application/json.
  • "urlencoded" (default): application/x-www-form-urlencoded.
  • "multipart": a FormData is built and the browser sets the Content-Type with its boundary. You can also pass your own FormData.
await Neysla.post({
  url: "https://www.my-domain.com/api/users",
  headers: { Authorization: "Bearer <token>" },
  requestType: "json",
  body: {
    first_name: "Roberto",
    last_name: "Magallanes",
    active: false,
  },
});

await Neysla.patch({
  url: "https://www.my-domain.com/api/users/10",
  requestType: "json",
  body: { active: true },
});

await Neysla.put({
  url: "https://www.my-domain.com/api/users/10",
  requestType: "json",
  body: { first_name: "Roberto", last_name: "Magallanes", active: true },
});

await Neysla.remove({ url: "https://www.my-domain.com/api/users/10" });

The response

Every successful request resolves with a NeyslaResponse<T> object:

Attribute or methodTypeDescription
statusnumberHTTP status code.
statusTextstringStatus text.
dataTResponse body, read according to responseType.
dataTypeNeyslaResponseTypeThe responseType it was read with.
headersRecord<string, string>Response headers. Keys always arrive in lowercase.
urlstringURL the request was sent to.
getHeader(name)string | nullA specific header; the lookup is case-insensitive.

With TypeScript you can type data:

interface User {
  id: number;
  first_name: string;
}

const { data } = await Neysla.get<User[]>({
  url: "https://www.my-domain.com/api/users",
});

Errors

  • If the configuration is invalid (for example, url is missing), the promise rejects with a TypeError.
  • If the server answers with a status >= 300 (or the network fails), the promise rejects with the same response object, so you can read status and data:
try {
  await Neysla.get({ url: "https://www.my-domain.com/api/users/999" });
} catch (error) {
  if (error instanceof TypeError) {
    // invalid configuration
  } else {
    console.log(error.status, error.data); // e.g. 404 and the error body
  }
}

Transfer progress

In the browser, when you set progress, Neysla uses XMLHttpRequest instead of fetch so it can report the native event. In Node.js the option is ignored.

const file = document.querySelector<HTMLInputElement>("#avatar")!.files![0];

await Neysla.post({
  url: "https://www.my-domain.com/api/avatars",
  requestType: "multipart",
  body: { file, name: "My avatar" },
  progress(event) {
    if (event.lengthComputable) {
      console.log(`${Math.round((event.loaded / event.total) * 100)} %`);
    }
  },
});

Neysla as a modeler

Model your RESTful API's nested resources once with Neysla (init, setModel and delimiters) and reuse them with global configuration per modeler.

In a well-designed RESTful API, resources are nested: in https://api.example.com/courses/2305/sections/2465, courses and sections are the static parts of the resource, and 2305 and 2465 are the dynamic parts (the identifiers).

Neysla builds on that structure: you define each resource once by its static parts and, on every request, you only pass the dynamic ones. Models are reused across your whole application, in the browser or in Node.js 18+.

An example API

Throughout this page we’ll model an API published at https://www.my-domain.com/api/ with three nested resources:

  • Users: user and user/:user_id.
  • A user’s contacts: user/:user_id/contact and user/:user_id/contact/:contact_id.
  • A contact’s phone numbers: user/:user_id/contact/:contact_id/phone and .../phone/:phone_id.

Initializing Neysla

Create an instance and call init with your API’s configuration. init is asynchronous and returns an object with one modeler per configuration, keyed by its name:

import { Neysla } from "neysla";

const neysla = new Neysla();

const modelers = await neysla.init({
  name: "myApi",
  url: "https://www.my-domain.com/api/",
  headers: { Authorization: "Bearer <token>" },
  params: { foo: "bar" },
  requestType: "json",
});

The init configuration applies to every request made through that modeler:

AttributeTypeRequiredDescription
namestringYesModeler name; its key in the object init returns.
urlstringYesBase of every model URL.
headersRecord<string, string>NoGlobal headers.
paramsNeyslaParamsNoGlobal query parameters.
bodyRecord<string, unknown>NoBody fields sent on every post, patch, put and remove.
requestType"json" | "multipart" | "urlencoded"NoDefault body encoding (urlencoded when omitted).
responseTypeNeyslaResponseTypeNoDefault response reading (json when omitted).
credentialsRequestCredentialsNoDefault credentials policy.

If the configuration is invalid (missing name or url, or an attribute of the wrong type), init rejects with a TypeError that names the failing modeler.

Defining models

Each modeler exposes setModel, which takes a resource’s static parts: a string for a top-level resource or an array for a nested one.

const api = modelers.myApi;

const user = api.setModel("user");
const userContact = api.setModel(["user", "contact"]);
const userContactPhone = api.setModel(["user", "contact", "phone"]);

So the contacts resource (user/:user_id/contact/:contact_id) breaks down into:

  • https://www.my-domain.com/api/: the base, set in url at initialization.
  • user and contact: the static parts, passed to setModel.
  • :user_id and :contact_id: the dynamic parts, passed on each request as delimiters.

The same logic works for resources nested at any depth. If setModel receives anything other than a string or an array, it throws a TypeError.

Making requests with models

Every model exposes get, head, post, patch, put and remove (the last one sends DELETE). All of them take an optional object:

OptionTypeDescription
delimitersstring | number | Array<string | number>The resource’s dynamic parts, in order.
paramsNeyslaParamsMerged with the global ones; the request’s win.
headersRecord<string, string>Merged with the global ones; the request’s win.
bodyRecord<string, unknown> | FormDataMerged with the global body (only for methods with a body).
requestTypeNeyslaRequestTypeOverrides the global one for this request.
responseTypeNeyslaResponseTypeOverrides the global one for this request.
credentialsRequestCredentialsOverrides the global one for this request.
progress(event: ProgressEvent) => voidTransfer progress (browser only).
Delimiters

A model with N static parts accepts N or N − 1 delimiters:

  • With N − 1 you target the collection: ["user", "contact"] + [12] → user/12/contact.
  • With N you target one item: ["user", "contact"] + [12, 4] → user/12/contact/4.

Any other count rejects the request with an error (“Incorrect relation between name and delimiters”).

GET
await user.get();
// GET https://www.my-domain.com/api/user?foo=bar

await user.get({ delimiters: 10, responseType: "blob" });
// GET https://www.my-domain.com/api/user/10?foo=bar (response as a Blob)

await user.get({ params: { order: "age", foo: "notBar" } });
// GET https://www.my-domain.com/api/user?foo=notBar&order=age

await userContactPhone.get({
  delimiters: [1, 500],
  params: { page: 7, perPage: 35 },
});
// GET https://www.my-domain.com/api/user/1/contact/500/phone?foo=bar&page=7&perPage=35
POST, PATCH, PUT and DELETE with models
await userContact.post({
  delimiters: 12,
  params: { foo: "notBar" },
  body: { name: "Bart", phone_type: "mobile" },
});
// POST https://www.my-domain.com/api/user/12/contact?foo=notBar

await userContact.patch({
  delimiters: [12, 4],
  body: { name: "Bart" },
});
// PATCH https://www.my-domain.com/api/user/12/contact/4?foo=bar

await userContact.remove({ delimiters: [12, 4] });
// DELETE https://www.my-domain.com/api/user/12/contact/4?foo=bar

Responses and errors work just like in direct usage: a status >= 300 rejects the promise with the response object.

Multiple modelers

If your application talks to more than one API, pass an array to init. Each configuration has its own base, headers and defaults:

const { usersApi, storageApi } = await neysla.init([
  {
    name: "usersApi",
    url: "https://users.my-domain.com/v1/",
    headers: { Authorization: "Bearer <token>" },
    requestType: "json",
  },
  {
    name: "storageApi",
    url: "https://storage.my-domain.com/",
    requestType: "multipart",
    responseType: "blob",
  },
]);

const profile = usersApi.setModel("profile");
const files = storageApi.setModel(["bucket", "file"]);

await profile.get({ delimiters: "me" });
await files.get({ delimiters: ["avatars", "marcos.webp"] });

Here only usersApi sends the authorization header; storageApi uploads as multipart and downloads as a Blob without repeating it on every call.

Need something similar?

Tell me what you have in mind and let's talk.