/nhost-js-sdk

Nhost JavaScript SDK

Primary LanguageJavaScript

nhost-js-sdk

Nhost js sdk to handle Auth and Storage.

Installation

npm install --save nhost-js-sdk

Setup

in ex /src/nhost/index.js:

import nhost from 'nhost-js-sdk';

const config = {
  endpoint: process.env.REACT_APP_BACKEND_ENDPOINT,
};

nhost.initializeApp(config);

const auth = nhost.auth();
const storage = nhost.storage();

export {
  auth,
  storage
};

Usage across in your app

import { auth, storage } from './path-to-nhost/index.js';

Auth

Register

register_data is optional

try {
  await auth.register(email, username, password, register_data);
} catch (e) {
  // handle error
}

Login

try {
  await auth.login(username, password);
} catch (e) {
  // handle error
}

Login as an anonymous user

try {
  await auth.signInAnonymously();
} catch (e) {
  // handle error
}

Logout

  auth.logout();

onAuthStateChanged

auth.onAuthStateChanged(data => {
  console.log('auth state changed!');
  console.log({data});
});

Activate account

try {
  await auth.activate_account(secret_token);
} catch (e) {
  // handle error
}

New password

try {
  await auth.new_password(secret_token, new_password);
} catch (e) {
  // handle error
}

Storage

Upload file

metadata is optional onUploadProgress is optional

try {
  await storage.put(path, file, metadata, onUploadProgress);
} catch (e) {
  // handle error
}

Delete file

try {
  await storage.delete(path);
} catch (e) {
  // handle error
}

Get downloadable URL of file

try {
  await storage.getDownloadURL(path);
} catch (e) {
  // handle error
}

React Native

For React Native you can pass in asyncStorage for nhost to use instead of the default localStorage.

import nhost from 'nhost-js-sdk';
import { AsyncStorage } from 'react-native';
import { BACKEND_ENDPOINT } from '../config';

const config = {
  endpoint: 'https://backend-xxxxxx.nhost.io/'
  storage: AsyncStorage
};

export default new nhost(config);