2.0.1 • Published 1 year ago

@xano/js-sdk v2.0.1

Weekly downloads
-
License
ISC
Repository
gitlab
Last release
1 year ago

Xano JavaScript SDK

The Xano JavaScript SDK is built in pure TypeScript. Under the hood the SDK uses Axios which is not only supported by all modern browsers but allows us to be compatible with NodeJS as well.

Questions, comments or suggestions? Let us know in the Xano Community

npm version

What is Xano?

Xano is the fastest way to build a powerful, scalable backend for your app without code.

Xano gives you a scalable server, a flexible database, and a NO CODE API builder that can transform, filter, and integrate with data from anywhere. We want to enable you to validate AND grow your ideas quickly without limits or any of the barriers you might have encountered using other tools. :muscle:

Xano Links

Installation

Include our script tag directly from jsDelivr:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@xano/js-sdk@latest/dist/xano.min.js"></script>

OR use npm to install the Xano JS SDK module:

npm  install  @xano/js-sdk

OR use our pre-bundled JS bundle:

<script  type="text/javascript"  src="dist/xano.min.js"></script>

NodeJS

NodeJS users should use our XanoNodeClient instead of XanoClient. The documentation is the same, it just takes care of some inconsistencies from the web behind the scenes.

Since NodeJS isn't a browser, the storage configuration is defaulted to XanoObjectStorage.

Examples

Pre-baked Examples

Examples for all methods and simple use-cases can be found in the /examples folder.

Uploading a file

Uploading a file can be a pretty complex process but we tried our best to make it as easy as possible - simply include the file as a parameter just like you would any other:

const  file = document.getElementById("file").files[0];

xano.post("/file_upload", {
	file:  file,
}).then(
	(response) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

NodeJS users should refer to our XanoFile class.

Connecting to Realtime

Connecting to realtime is as simple as supplying a channel name and listening for events. The client will automatically authenticate if the authToken setting is set.

import { XanoClient, XanoSessionStorage } from  "@xano/js-sdk";

const  xano = new  XanoClient({
	instanceBaseUrl:  "https://x8ki-letl-twmt.n7.xano.io/",
	realtimeConnectionHash: "1lK90n16tnnylJpJ0Xa7Km6_KxA",
});

const channel = xano.channel("some_channel");

// Listening to all events
channel.on(function(action) {
	console.log("Received action", action);
});

// Listening to specific events (full list in src/enums/realtime-action.ts)
channel.on("message", function(action) {
	console.log("Received message", action);
});

channel.message({ message: "Hello world!" });

Client Documentation

XanoClient

This is the primary client class of Xano. It can be instantiated with the following parameters:

ParamTypeDefaultDescription
apiGroupBaseUrlstring \| nullnullAPI Group Base URL can be found on the API Group dashboard
authTokenstring \| nullnullAuth token generated in Xano from a login route (ex. /auth/login). Depending on storage this value will persist when set/cleared
customAxiosRequestConfigPartial<AxiosRequestConfig>{}For extreme edge cases, you can override the default Axios config that the SDK uses. AxiosRequestConfig Documentation. Useful for ignoring SSL cert issues, etc
dataSourcestring \| nullnullName of the Xano Data Source to use as the X-Data-Source header
instanceBaseUrlstring \| nullnullURL of the Xano instance to make requests to (ex. https://x8ki-letl-twmt.n7.xano.io/)
realtimeAuthTokenstring \| nullnullAuth token used when connecting to realtime. NOTICE: If not present, it will default to authToken until sunset on July 1st, 2024, then it will be required for realtime authentication. More details...
realtimeConnectionHashstring \| nullnullThe connection hash found on the realtime settings panel within your instance workspace
responseObjectPrefixstring \| nullnullIf the API response body is an object or an array of objects then this will prefix all keys with this value
storageXanoBaseStorageXanoLocalStorageThe storage mechanism where we store persistant information like authToken

Usage:

import { XanoClient } from  "@xano/js-sdk";

const  xano = new  XanoClient({
	apiGroupBaseUrl:  "https://x8ki-letl-twmt.n7.xano.io/api:jVuUQATw",
});

XanoClient.hasAuthToken

Checks to see if the authToken has been set.

Usage:

xano.setAuthToken("eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBM....");

console.log(xano.hasAuthToken()); // true

XanoClient.setAuthToken

Sets the authentication token which makes future requests authenticated.

Depending on storage when configuring XanoClient this value could persist across browser reloads.

ParamTypeDescription
authTokenstring \| nullCan be created from the /auth/login endpoint. null will clear the token

Usage:

xano.setAuthToken("eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBM....");

XanoClient.hasRealtimeAuthToken

Checks to see if the realtimeAuthToken has been set.

Usage:

xano.setRealtimeAuthToken("eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBM....");

console.log(xano.hasRealtimeAuthToken()); // true

XanoClient.setRealtimeAuthToken

Sets the realtime authentication token which is used on new realtime connections.

Depending on storage when configuring XanoClient this value could persist across browser reloads.

ParamTypeDescription
authTokenstring \| nullCan be created from the /auth/login endpoint. null will clear the token

Usage:

xano.setRealtimeAuthToken("eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBM....");
xano.realtimeReconnect();

XanoClient.hasDataSource

Checks to see if the dataSource has been set.

Usage:

xano.setDataSource("develop");

console.log(xano.hasDataSource()); // true

XanoClient.setDataSource

Sets the data source which makes future requests include the X-Data-Source header.

More information about data sources can be found here

ParamTypeDescription
dataSourcestring \| nullThe name of the data source to use

Usage:

xano.setDataSource("develop");

XanoClient.get

Makes a GET HTTP request to Xano.

This function returns a Promise that resolves to XanoResponse on success and XanoRequestError on failure.

ParamTypeRequiredDescription
endpointstringyesThe endpoint starting with a / (ex. /users)
paramsobjectnoURL params to attach to the request
headersobjectnoKey/value pair of headers to send with the request

Usage:

xano.get("/users", {
	sort_by:  "name",
}).then(
	(response) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

XanoClient.post

Makes a POST HTTP request to Xano.

This function returns a Promise that resolves to XanoResponse on success and XanoRequestError on failure.

ParamTypeRequiredDescription
endpointstringyesThe endpoint starting with a / (ex. /users)
paramsobjectnobody params to attach to the request
headersobjectnoKey/value pair of headers to send with the request

Usage:

xano.post("/users", {
	first_name:  "Justin",
	last_name:  "Albrecht",
}).then(
	(response) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

XanoClient.patch

Makes a PATCH HTTP request to Xano.

This function returns a Promise that resolves to XanoResponse on success and XanoRequestError on failure.

ParamTypeRequiredDescription
endpointstringyesThe endpoint starting with a / (ex. /users)
paramsobjectnobody params to attach to the request
headersobjectnoKey/value pair of headers to send with the request

Usage:

xano.patch("/users", {
	first_name:  "Justin",
}).then(
	(response) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

XanoClient.put

Makes a PUT HTTP request to Xano.

This function returns a Promise that resolves to XanoResponse on success and XanoRequestError on failure.

ParamTypeRequiredDescription
endpointstringyesThe endpoint starting with a / (ex. /users)
paramsobjectnobody params to attach to the request
headersobjectnoKey/value pair of headers to send with the request

Usage:

xano.put("/users", {
	last_name:  "Albrecht",
}).then(
	(response) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

XanoClient.delete

Makes a DELETE HTTP request to Xano.

This function returns a Promise that resolves to XanoResponse on success and XanoRequestError on failure.

ParamTypeRequiredDescription
endpointstringyesThe endpoint starting with a / (ex. /users)
paramsobjectnobody params to attach to the request
headersobjectnoKey/value pair of headers to send with the request

Usage:

xano.delete("/users/1", {
	optional:  "abc",
}).then(
	(response) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

XanoClient.head

Makes a HEAD HTTP request to Xano.

This function returns a Promise that resolves to XanoResponse on success and XanoRequestError on failure.

ParamTypeRequiredDescription
endpointstringyesThe endpoint starting with a / (ex. /users)
paramsobjectnoURL params to attach to the request
headersobjectnoKey/value pair of headers to send with the request

Usage:

xano.head("/users/1", {
	optional:  "abc",
}).then(
	(response) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

XanoResponse

The response class of a successful GET/POST/PATCH/PUT/DELETE/HEAD request.

FunctionParamsReturn TypeDescription
getBodyobjectPrefix: stringanyIf the API response is JSON it will be the JSON encoded resultIf the API response is text then it will be the text resultIf objectPrefix is set and the response is a JSON object or an array of objects then all keys will be prefixed with this valueobjectPrefix will take priority over setting it on XanoClient through responseObjectPrefix
getHeadersobjectkey/value pairs of the response headers
getStatusCodenumberThe status code of the HTTP request

Usage:

xano.get("/users").then((response) => {
	const  body = response.getBody();
	const  headers = response.getHeaders();
	const  statusCode = response.getStatusCode();
});

XanoRequestError

The response class of a failed GET/POST/PATCH/PUT/DELETE/HEAD request.

This class extends the JS Error class.

ParamTypeReturn TypeDescription
getResponsefunctionXanoResponseReturns XanoResponse to get more information like HTTP status, headers, etc
messagestringstringA generic human readable error message

Usage:

xano.get("/users").then(
	(response) => {},
	(error) => {
		const  xanoHttpResponse = error.getResponse();
		const  body = xanoHttpResponse.getBody();
		const  headers = xanoHttpResponse.getHeaders();
		const  statusCode = xanoHttpResponse.getStatusCode();
	}
);

XanoFile

XanoFile is a class for NodeJS only!

The XanoFile class is required to upload a file from the NodeJS file system.

ParamTypeDescription
namestringThe name of the file
bufferBufferBuffer of the file

Usage:

const  fs = require("fs/promises");
const  fileName = "512x512bb.jpg";

fs.readFile("./" + fileName).then(
	(imageBuffer) => {
		const  xImage = new  XanoFile(fileName, imageBuffer);

		xano.post("/file_upload", {
			image:  xImage,
		}).then(
			(response) => {
				// Success!
			},
			(error) => {
				// Error
			}
		);
	}
);

XanoBaseStorage

The XanoBaseStorage class is extended for storing/retrieving information like the authToken.

Xano supplies four Storage classes by default:

Class NameStorage MechanismPersistantNodeJS Compatible
XanoCookieStoragedocument.cookieyesno
XanoLocalStoragelocalStorageyesno
XanoSessionStoragesessionStorageyesno
XanoObjectStorageObjectnoyes

Each class that extends XanoBaseStorage share the following functions:

FunctionParamsReturn TypeDescription
clearvoidClears all storage keys
getAllRecord<string, string>Returns all data stored in XanoBaseStorage
getItemkey: stringstring \| nullReturns the value for the key, or null if not set
removeItemkey: stringvoidRemoves the key and value from storage
setItemkey: string, value: stringvoidUpdates storage for key with value

Usage:

import { XanoClient, XanoSessionStorage } from  "@xano/js-sdk";

const  xano = new  XanoClient({
	apiGroupBaseUrl:  "https://x8ki-letl-twmt.n7.xano.io/api:jVuUQATw",
	storage:  new  XanoSessionStorage(),
});

Realtime Documentation

Every Xano instance comes with a realtime socket server that can be enabled on a per-workspace basis that supports Xano to client messaging, client to public channel messaging, client to private channel messaging, and client to client (private) messaging.

XanoClient.channel

Connects the XanoClient to a realtime websocket channel.

This function returns an instance of XanoRealtimeChannel

ParamTypeRequiredDescription
channelstringyesThe channel name you want to join
optionsPartial<IRealtimeChannelOptionsnoChannel options to connect to the channel with

Usage:

const channel = xano.channel("stats", {
	presence:  true,
});

XanoClient.realtimeReconnect

If you are connected to the realtime websocket server this will trigger a reconnect. This function is usefull after updating your realtimeAuthToken to trigger re-authentication.

Usage:

xano.setRealtimeAuthToken("eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBM....");
xano.realtimeReconnect();

XanoRealtimeChannel.on (all events)

The on returns an event stream that can be subscribed to with a success and error function:

ParamTypeRequiredDescription
onActionCallableFunction<XanoRealtimeAction>yesA callback function that gets called when the channel receives an action
onErrorCallableFunction<XanoRealtimeAction>noA callback function that gets called when the channel receives an error message

Usage:

channel.on(
	(action) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

XanoRealtimeChannel.on (specific events)

The on returns an event stream that can be subscribed to with an action, success function, and error function:

ParamTypeRequiredDescription
actionERealtimeActionyesThe action you want to subscribe to
onActionCallableFunction<XanoRealtimeAction>yesA callback function that gets called when the channel receives an action
onErrorCallableFunction<XanoRealtimeAction>noA callback function that gets called when the channel receives an error message

Usage:

// Using the string action
channel.on("message", 
	(action) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

// Using the typescript enum:
channel.on(ERealtimeAction.Message, 
	(action) => {
		// Success!
	},
	(error) => {
		// Failure
	}
);

XanoRealtimeChannel.message

Sends a message from the client to the channel

ParamTypeRequiredDescription
payloadanyyesAny JSON stringable payload to send to the channel
optionsPartial<XanoRealtimeActionOptions>noAction options to send with the action

Usage:

// Send a message to only other authenticated users in a channel
channel.message({ message: "Hello world!" }, {
	authenticated: true
});

XanoRealtimeChannel.getPresence

Sends a message from the client to the channel.

Presence is only available on channels joined with XanoRealtimeChannelOptions.presence set to true

Returns an array of XanoRealtimeClient

Usage:

const users = channel.getPresence();

XanoRealtimeChannel.history

Sends a message to realtime requesting the latest channel history. The response will be sent through the history action

History is only available on channels with message history enabled

Usage:

channel.history();

channel.on('history', function(action) {
	console.log('history', action);
});

XanoRealtimeChannel.destroy

Leaves the channel and disconnects from the realtime websocket server if its the last open channel. You will need to create a new XanoRealtimeChannel instance to rejoin or interact with the channel again.

Usage:

channel.destroy();

XanoRealtimeClient.message

Sends a private message directly to the XanoRealtimeClient client.

Usage:

const presence = channel.getPresence();

for (const client of presence) {
	client.message({ message: "Saying hello to everyone in private!" });
}

XanoRealtimeClient.history

Sends a message to realtime requesting the latest channel history. The response will be sent through the history action

History is only available on channels with message history enabled

Usage:

client.history();

channel.on('history', function(action) {
	console.log('history', action);
});

XanoRealtimeChannelOptions

Leaves the channel and disconnects from the realtime websocket server if its the last open channel. You will need to create a new XanoRealtimeChannel instance to rejoin or interact with the channel again.

ParamTypeDefaultDescription
historybooleanfalseReturns the channel message history on join (if its enabled on a channel)
presencebooleanfalseSubscribes to channel presence to see who else is in the channel and events when others join/leave
queueOfflineActionsbooleantrueIn the event of a disconnect, or when sending actions before the channel connection is established, actions will be put in a queue and sent as soon as the connection is established

XanoRealtimeClient

Presence user or initiator of a action

ParamTypeDefaultDescription
extrasRecord<string, any>{}When authenticated this is the extras that are configured with the auth token
permissionsRecord<{ dbo_id: number; row_id: number}>{ dbo_id: 0, row_id: 0}Permissions are set through the authToken supplied when configuring XanoClient. dbo_id is the table ID that the client is authenticated with, row_id is the row of the client
socketIdstringInternal socket ID used for sending private actions

XanoRealtimeAction

The action payload sent and received through the XanoRealtimeChannel

ParamTypeDefaultDescription
client?XanoRealtimeClient{}The authenticated client that initiated the action
actionERealtimeActionThe action sent/received
optionsXanoRealtimeActionOptionsOptions sent with the action
payloadRecord<string, any>The payload sent with the action

XanoRealtimeActionOptions

The action options when sending and receiving actions through the XanoRealtimeChannel.message

ParamTypeDefaultDescription
authenticated?booleanfalseIf the action received is for authenticated clients only
channelstringThe channel name that the action is intended for
socketIdstringThe socketId for the recipient or sender of the action

TypeScript support

This package includes TypeScript declarations. We support projects using TypeScript versions >= 3.1.

2.0.1

1 year ago

2.0.0

1 year ago

1.0.36

1 year ago

1.0.33

1 year ago

1.0.32

1 year ago

1.0.31

1 year ago

1.0.30

1 year ago

1.0.35

1 year ago

1.0.29

1 year ago

1.0.28

1 year ago

1.0.26

1 year ago

1.0.27

1 year ago

1.0.25

1 year ago

1.0.22

1 year ago

1.0.24

1 year ago

1.0.23

1 year ago

1.0.21

2 years ago

1.0.20

2 years ago

1.0.19

2 years ago

1.0.18

3 years ago

1.0.17

3 years ago

1.0.16

3 years ago

1.0.15

3 years ago

1.0.14

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.11

3 years ago

1.0.10

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago