Main entry point for the Nhost JavaScript SDK. This package provides a unified client for interacting with Nhost services:
  • Authentication
  • Storage
  • GraphQL
  • Functions

Import

import { createClient } from '@nhost/nhost-js'

Usage

Create a client instance to interact with Nhost services:
const nhost = createClient({
  subdomain,
  region
})

// Sign in with email/password
// This will create a session and persist it in the storage
// Subsequent calls will use the session from the storage
// If the session is about to expire, it will be refreshed
// automatically
await nhost.auth.signUpEmailPassword({
  email,
  password
})

// upload a couple of files
const uplFilesResp = await nhost.storage.uploadFiles({
  'file[]': [
    new File(['test1'], 'file-1', { type: 'text/plain' }),
    new File(['test2 is larger'], 'file-2', { type: 'text/plain' })
  ]
})
console.log(JSON.stringify(uplFilesResp, null, 2))
// {
//   "data": {
//     "processedFiles": [
//       {
//         "id": "c0e83185-0ce5-435c-bd46-9841adc30699",
//         "name": "file-1",
//         "size": 5,
//         "bucketId": "default",
//         "etag": "\"5a105e8b9d40e1329780d62ea2265d8a\"",
//         "createdAt": "2025-05-09T17:26:04.579839+00:00",
//         "updatedAt": "2025-05-09T17:26:04.589692+00:00",
//         "isUploaded": true,
//         "mimeType": "text/plain",
//         "uploadedByUserId": "",
//         "metadata": null
//       },
//       {
//         "id": "3f189004-21fd-42d0-be1d-1ead021ab167",
//         "name": "file-2",
//         "size": 15,
//         "bucketId": "default",
//         "etag": "\"302e888c5e289fe6b02115b748771ee9\"",
//         "createdAt": "2025-05-09T17:26:04.59245+00:00",
//         "updatedAt": "2025-05-09T17:26:04.596831+00:00",
//         "isUploaded": true,
//         "mimeType": "text/plain",
//         "uploadedByUserId": "",
//         "metadata": null
//       }
//     ]
//   },
//   "status": 201,
//   "headers": {
//     "content-length": "644",
//     "content-type": "application/json; charset=utf-8",
//     "date": "Fri, 09 May 2025 17:26:04 GMT"
//   }
// }

// make a GraphQL request to list the files
const graphResp = await nhost.graphql.request({
  query: `
     query {
       files {
         name
         size
         mimeType
       }
     }
   `
})

console.log(JSON.stringify(graphResp, null, 2))
// {
//   "body": {
//     "data": {
//       "files": [
//         {
//           "name": "file-1",
//           "size": 5,
//           "mimeType": "text/plain"
//         },
//         {
//           "name": "file-2",
//           "size": 15,
//           "mimeType": "text/plain"
//         }
//       ]
//     }
//   },
//   "status": 200,
//   "headers": {}
// }

// make a request to a serverless function
const funcResp = await nhost.functions.post('/helloworld', {
  message: 'Hello, World!'
})
console.log(JSON.stringify(funcResp.body, null, 2))
// {
//   "message": "Hello, World!"
// }

Interfaces

NhostClient

Main client class that provides unified access to all Nhost services. This class serves as the central interface for interacting with Nhost’s authentication, storage, GraphQL, and serverless functions capabilities.

Properties

auth

auth: Client
Authentication client providing methods for user sign-in, sign-up, and session management. Use this client to handle all authentication-related operations.

functions

functions: Client
Functions client providing methods for invoking serverless functions. Use this client to call your custom serverless functions deployed to Nhost.

graphql

graphql: Client
GraphQL client providing methods for executing GraphQL operations against your Hasura backend. Use this client to query and mutate data in your database through GraphQL.

sessionStorage

sessionStorage: SessionStorage
Storage implementation used for persisting session information. This handles saving, retrieving, and managing authentication sessions across requests.

storage

storage: Client
Storage client providing methods for file operations (upload, download, delete). Use this client to manage files in your Nhost storage.

Methods

clearSession()

clearSession(): void;
Clear the session from storage. This method removes the current authentication session, effectively logging out the user. Note that this is a client-side operation and doesn’t invalidate the refresh token on the server, which can be done with nhost.auth.signOut({refreshToken: session.refreshTokenId}). If the middle updateSessionFromResponseMiddleware is used, the session will be removed from the storage automatically and calling this method is not necessary.
Returns
void
Example
// Log out the user
nhost.clearSession()

getUserSession()

getUserSession(): null | Session;
Get the current session from storage. This method retrieves the authenticated user’s session information if one exists.
Returns
null | Session The current session or null if no session exists
Example
const session = nhost.getUserSession()
if (session) {
  console.log('User is authenticated:', session.user.id)
} else {
  console.log('No active session')
}

refreshSession()

refreshSession(marginSeconds: number): Promise<null | Session>;
Refresh the session using the current refresh token in the storage and update the storage with the new session. This method can be used to proactively refresh tokens before they expire or to force a refresh when needed.
Parameters
ParameterTypeDefault valueDescription
marginSecondsnumber60The number of seconds before the token expiration to refresh the session. If the token is still valid for this duration, it will not be refreshed. Set to 0 to force the refresh.
Returns
Promise<null | Session> The new session or null if there is currently no session or if refresh fails
Example
// Refresh token if it's about to expire in the next 5 minutes
const refreshedSession = await nhost.refreshSession(300)

// Force refresh regardless of current token expiration
const forcedRefresh = await nhost.refreshSession(0)

NhostClientOptions

Configuration options for creating an Nhost client

Extended by

Properties

authUrl?

optional authUrl: string;
Complete base URL for the auth service (overrides subdomain/region)

functionsUrl?

optional functionsUrl: string;
Complete base URL for the functions service (overrides subdomain/region)

graphqlUrl?

optional graphqlUrl: string;
Complete base URL for the GraphQL service (overrides subdomain/region)

region?

optional region: string;
Nhost region (e.g., ‘eu-central-1’). Used to construct the base URL for services for the Nhost cloud.

storage?

optional storage: SessionStorageBackend;
Storage backend to use for session persistence. If not provided, the SDK will default to localStorage in the browser or memory in other environments.

storageUrl?

optional storageUrl: string;
Complete base URL for the storage service (overrides subdomain/region)

subdomain?

optional subdomain: string;
Nhost project subdomain (e.g., ‘abcdefgh’). Used to construct the base URL for services for the Nhost cloud.

NhostServerClientOptions

Configuration options for creating an Nhost client

Extends

Properties

authUrl?

optional authUrl: string;
Complete base URL for the auth service (overrides subdomain/region)
Inherited from
NhostClientOptions.authUrl

functionsUrl?

optional functionsUrl: string;
Complete base URL for the functions service (overrides subdomain/region)
Inherited from
NhostClientOptions.functionsUrl

graphqlUrl?

optional graphqlUrl: string;
Complete base URL for the GraphQL service (overrides subdomain/region)
Inherited from
NhostClientOptions.graphqlUrl

region?

optional region: string;
Nhost region (e.g., ‘eu-central-1’). Used to construct the base URL for services for the Nhost cloud.
Inherited from
NhostClientOptions.region

storage

storage: SessionStorageBackend
Storage backend to use for session persistence in server environments. Unlike the base options, this field is required for server-side usage as the SDK cannot auto-detect an appropriate storage mechanism.
Overrides
NhostClientOptions.storage

storageUrl?

optional storageUrl: string;
Complete base URL for the storage service (overrides subdomain/region)
Inherited from
NhostClientOptions.storageUrl

subdomain?

optional subdomain: string;
Nhost project subdomain (e.g., ‘abcdefgh’). Used to construct the base URL for services for the Nhost cloud.
Inherited from
NhostClientOptions.subdomain

Functions

createClient()

function createClient(options: NhostClientOptions): NhostClient
Creates and configures a new Nhost client instance optimized for client-side usage. This helper method instantiates a fully configured Nhost client by:
  • Instantiating the various service clients (auth, storage, functions and graphql)
  • Auto-detecting and configuring an appropriate session storage (localStorage in browsers, memory otherwise)
  • Setting up a sophisticated middleware chain for seamless authentication management:
    • Automatically refreshing tokens before they expire
    • Attaching authorization tokens to all service requests
    • Updating the session storage when new tokens are received
This method includes automatic session refresh middleware, making it ideal for client-side applications where long-lived sessions are expected.

Parameters

ParameterTypeDescription
optionsNhostClientOptionsConfiguration options for the client

Returns

NhostClient A configured Nhost client

Example

// Create client using Nhost cloud default URLs
const nhost = createClient({
  subdomain: 'abcdefgh',
  region: 'eu-central-1'
})

// Create client with custom service URLs
const customNhost = createClient({
  authUrl: 'https://auth.example.com',
  storageUrl: 'https://storage.example.com',
  graphqlUrl: 'https://graphql.example.com',
  functionsUrl: 'https://functions.example.com'
})

// Create client using cookies for storing the session
import { CookieStorage } from '@nhost/nhost-js/session'

const nhost = createClient({
  subdomain: 'abcdefgh',
  region: 'eu-central-1',
  storage: new CookieStorage({
    secure: import.meta.env.ENVIRONMENT === 'production'
  })
})

createServerClient()

function createServerClient(options: NhostServerClientOptions): NhostClient
Creates and configures a new Nhost client instance optimized for server-side usage. This helper method instantiates a fully configured Nhost client specifically designed for:
  • Server components (in frameworks like Next.js or Remix)
  • API routes and middleware
  • Backend services and server-side rendering contexts
Key differences from the standard client:
  • Requires explicit storage implementation (must be provided)
  • Disables automatic session refresh middleware (to prevent race conditions in server contexts)
  • Still attaches authorization tokens and updates session storage from responses
The server client is ideal for short-lived request contexts where session tokens are passed in (like cookie-based authentication flows) and automatic refresh mechanisms could cause issues with concurrent requests.

Parameters

ParameterTypeDescription
optionsNhostServerClientOptionsConfiguration options for the server client (requires storage implementation)

Returns

NhostClient A configured Nhost client optimized for server-side usage

Example

// Example with cookie storage for Next.js API route or server component
import { cookies } from 'next/headers'

const nhost = createServerClient({
  region: process.env['NHOST_REGION'] || 'local',
  subdomain: process.env['NHOST_SUBDOMAIN'] || 'local',
  storage: {
    // storage compatible with Next.js server components
    get: (): Session | null => {
      const s = cookieStore.get(key)?.value || null
      if (!s) {
        return null
      }
      const session = JSON.parse(s) as Session
      return session
    },
    set: (value: Session) => {
      cookieStore.set(key, JSON.stringify(value))
    },
    remove: () => {
      cookieStore.delete(key)
    }
  }
})

// Example with cookie storage for Next.js middleware
const nhost = createServerClient({
  region: process.env['NHOST_REGION'] || 'local',
  subdomain: process.env['NHOST_SUBDOMAIN'] || 'local',
  storage: {
    // storage compatible with Next.js middleware
    get: (): Session | null => {
      const raw = request.cookies.get(key)?.value || null
      if (!raw) {
        return null
      }
      const session = JSON.parse(raw) as Session
      return session
    },
    set: (value: Session) => {
      response.cookies.set({
        name: key,
        value: JSON.stringify(value),
        path: '/',
        httpOnly: false, //if set to true we can't access it in the client
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 60 * 60 * 24 * 30 // 30 days in seconds
      })
    },
    remove: () => {
      response.cookies.delete(key)
    }
  }
})

// Example for express reading session from a cookie

import express, { Request, Response } from 'express'
import cookieParser from 'cookie-parser'

app.use(cookieParser())

const nhostClientFromCookies = (req: Request) => {
  return createServerClient({
    subdomain: 'local',
    region: 'local',
    storage: {
      get: (): Session | null => {
        const s = req.cookies.nhostSession || null
        if (!s) {
          return null
        }
        const session = JSON.parse(s) as Session
        return session
      },
      set: (_value: Session) => {
        throw new Error('It is easier to handle the session in the client')
      },
      remove: () => {
        throw new Error('It is easier to handle the session in the client')
      }
    }
  })
}

generateServiceUrl()

function generateServiceUrl(
  serviceType: 'storage' | 'auth' | 'graphql' | 'functions',
  subdomain?: string,
  region?: string,
  customUrl?: string
): string
Generates a base URL for a Nhost service based on configuration

Parameters

ParameterTypeDescription
serviceType"storage" | "auth" | "graphql" | "functions"Type of service (auth, storage, graphql, functions)
subdomain?stringNhost project subdomain
region?stringNhost region
customUrl?stringCustom URL override if provided

Returns

string The base URL for the service