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
| Format | File | Use it when… |
|---|---|---|
| ESM | dist/esm/index.js | You use a modern bundler or native ES modules (recommended). |
| CJS | dist/cjs/index.cjs | Your Node.js environment uses require(). |
| IIFE / CDN | dist/cdn/neysla.min.js | You load the library with a <script> tag. |
| Types | dist/types/index.d.ts | Always: TypeScript picks them up automatically. |
Requirements
- Modern browsers with Fetch API support.
- Node.js 18 or later (the version where
fetchis 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.
| Method | HTTP verb | Sends a body |
|---|---|---|
Neysla.get(options) | GET | No |
Neysla.head(options) | HEAD | No |
Neysla.post(options) | POST | Yes |
Neysla.patch(options) | PATCH | Yes |
Neysla.put(options) | PUT | Yes |
Neysla.remove(options) | DELETE | Yes |
Request options
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
url | string | Yes | — | Full endpoint URL. |
params | Record<string, string | number | boolean | Array<string | number>> | No | — | Query string parameters. An array repeats the key (?tag=a&tag=b). |
headers | Record<string, string> | No | {} | Request headers. |
body | Record<string, unknown> | FormData | No | — | 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. |
credentials | RequestCredentials | No | — | Same as in fetch ("include" to send cookies cross-origin). |
progress | (event: ProgressEvent) => void | No | — | 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.stringifyandContent-Type: application/json."urlencoded"(default):application/x-www-form-urlencoded."multipart": aFormDatais built and the browser sets theContent-Typewith its boundary. You can also pass your ownFormData.
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 method | Type | Description |
|---|---|---|
status | number | HTTP status code. |
statusText | string | Status text. |
data | T | Response body, read according to responseType. |
dataType | NeyslaResponseType | The responseType it was read with. |
headers | Record<string, string> | Response headers. Keys always arrive in lowercase. |
url | string | URL the request was sent to. |
getHeader(name) | string | null | A 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,
urlis missing), the promise rejects with aTypeError. - If the server answers with a status
>= 300(or the network fails), the promise rejects with the same response object, so you can readstatusanddata:
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:
useranduser/:user_id. - A user’s contacts:
user/:user_id/contactanduser/:user_id/contact/:contact_id. - A contact’s phone numbers:
user/:user_id/contact/:contact_id/phoneand.../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:
| Attribute | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Modeler name; its key in the object init returns. |
url | string | Yes | Base of every model URL. |
headers | Record<string, string> | No | Global headers. |
params | NeyslaParams | No | Global query parameters. |
body | Record<string, unknown> | No | Body fields sent on every post, patch, put and remove. |
requestType | "json" | "multipart" | "urlencoded" | No | Default body encoding (urlencoded when omitted). |
responseType | NeyslaResponseType | No | Default response reading (json when omitted). |
credentials | RequestCredentials | No | Default 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 inurlat initialization.userandcontact: the static parts, passed tosetModel.:user_idand:contact_id: the dynamic parts, passed on each request asdelimiters.
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:
| Option | Type | Description |
|---|---|---|
delimiters | string | number | Array<string | number> | The resource’s dynamic parts, in order. |
params | NeyslaParams | Merged with the global ones; the request’s win. |
headers | Record<string, string> | Merged with the global ones; the request’s win. |
body | Record<string, unknown> | FormData | Merged with the global body (only for methods with a body). |
requestType | NeyslaRequestType | Overrides the global one for this request. |
responseType | NeyslaResponseType | Overrides the global one for this request. |
credentials | RequestCredentials | Overrides the global one for this request. |
progress | (event: ProgressEvent) => void | Transfer 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.