Nhost JS SDK

JavaScript SDK for handling Auth and Storage

#Installation

$ npm install nhost-js-sdk

or

$ yarn add nhost-js-sdk

#Setup

/src/utils/nhost
import { createClient } from "nhost-js-sdk";

const nhostClient = createClient({
  baseURL: "https://backend-url.nhost.app",
})

const auth = nhostClient.auth;
const storage = nhostClient.storage;

export { auth, storage };
Parameters
baseURLstringrequiredBackend URL
useCookiesbooleanoptionalUse cookies for auth (defaults to false)
refreshIntervalTimenumberoptionalAutorefresh interval in ms (defaults to Math.max(30 * 1000, JWTExpiresIn - 45000))
ssrbooleanoptionalEnable server-side rendering mode (defaults to typeof window === "undefined")
autoLoginbooleanoptionalAuto logins user (defaults to true)
clientStorageClientStorageoptionalStorage to use (defaults to window.localStorage)
clientStorageTypestringoptionalStorage type (defaults to web)

#Usage

import { auth, storage } from "src/utils/nhost";

Auth

Creating a user with email and password is done with register(). For OAuth, the login() function creates the user on the first login attempt.

auth.register({ email, password });

// with options
auth.register({
  email,
  password,
  options: { userData: { display_name: "Joe Doe" } },
});

Existing users can login with email and password or using an OAuth provider.

auth.login({ email, password });

// OAuth provider: google | github | linkedin ...
auth.login({ provider })

Users can logout via logout().

auth.logout();

To register a callback to run when the auth state changes (e.g., when a user logs out) is done via onAuthStateChanged().

auth.onAuthStateChanged((loggedIn) => {
  console.log("auth state changed!");
  console.log({ loggedIn });
});

To check if a user is logged in or not use isAuthenticated().

auth.isAuthenticated();

notes:

  • true means the user is logged in
  • false means the user is not logged in
  • null means that a request to login the user is ongoing.

For getting a user session's JWT Token use getJWTToken().

auth.getJWTToken();

And for its claims getClaim().

auth.getClaim("x-hasura-user-id");

To activate a user account use activate().

auth.activate(<ticket>);

For changing an account's email address without confirmation use changeEmail(). The user must be logged in.

auth.changeEmail(new_email);

Or with a confirmation email requestEmailChange().

auth.requestEmailChange(new_email);

To confirm the email change use confirmEmailChange() and pass in the ticket received with the email.

auth.confirmEmailChange(ticket);

For changing a user's password use changePassword().

auth.changePassword(oldPassword, newPassword);

Or with a confirmation email use requestPasswordChange().

auth.requestPasswordChange(email);

To confirm the password change use confirmPasswordChange().

auth.confirmPasswordChange(new_password, ticket);

To generate a MFA QR-code use MFAGenerate(). The user must be logged in.

auth.MFAGenerate();

Enabling MFA is done via enable().

auth.enable(code);

And disabling is done via disable().

auth.disable(code);

To login using MFA TOTP use MFATotp() and pass in the ticket returned by login() (when MFA is enabled).

auth.MFATotp(code, ticket);

Storage

Uploading a file is done using put().

storage.put(path, file, metadata?, onUploadProgress?);

To delete a file use delete().

storage.delete(path);

To get the metadata for a file use getMetadata().

storage.getMetadata(path);

Other environments

React Native

Install:

$ yarn add @react-native-community/async-storage

Installation instructions can be found at https://react-native-community.github.io/async-storage/docs/install.

import createClient from "nhost-js-sdk";
import AsyncStorage from "@react-native-async-storage/async-storage";

const nhostClient = createClient({
  baseURL: "https://backend-url.nhost.app",
  clientStorage: AsyncStorage,
  clientStorageType: "react-native",
});

const { auth, storage } = nhostClient;

export { auth, storage };

Ionic

import createClient from "nhost-js-sdk";
import { Plugins } from "@capacitor/core";
const { Storage } = Plugins;

const nhostClient = createClient({
  baseURL: "https://backend-url.nhost.app",
  clientStorage: Storage,
  clientStorageType: "capacitor
})

const auth = nhostClient.auth;
const storage = nhostClient.storage;

export { auth, storage };

Expo

Install:

$ expo install expo-secure-store

More info: https://docs.expo.io/versions/latest/sdk/securestore/.

import createClient from "nhost-js-sdk";
import * as SecureStore from "expo-secure-store";

const nhostClient = createClient({
  baseURL: "https://backend-url.nhost.app",
  clientStorage: SecureStore,
  clientStorageType: "expo-secure-storage",
})

const auth = nhostClient.auth;
const storage = nhostClient.storage;

export { auth, storage };