Thanks to visit codestin.com
Credit goes to docs.nhost.io

Skip to content

Main

Main entry point for the Nhost JavaScript SDK.

This package provides a unified client for interacting with Nhost services:

  • Authentication
  • Storage
  • GraphQL
  • Functions
import { createClient } from '@nhost/nhost-js'

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": "3357aada-b6c7-4af1-9655-1307ca2883a2",
// "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": "3357aada-b6c7-4af1-9655-1307ca2883a2",
// "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!"
// }

You can also create an admin client if needed. This client will have admin access to the database and will bypass permissions. Additionally, it can impersonate users and set any role or session variable.

IMPORTANT!!! Keep your admin secret safe and never expose it in client-side code.

const nhost = createNhostClient({
subdomain,
region,
configure: [
withAdminSession({
adminSecret: 'nhost-admin-secret',
role: 'user',
sessionVariables: {
'user-id': '54058C42-51F7-4B37-8B69-C89A841D2221'
}
})
]
})
// 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": "54058c42-51f7-4b37-8b69-c89a841d2221",
// "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": "54058c42-51f7-4b37-8b69-c89a841d2221",
// "metadata": null
// }
// ]
// },
// "status": 201,
// "headers": {
// "content-length": "644",
// "content-type": "application/json; charset=utf-8",
// "date": "Fri, 09 May 2025 17:26:04 GMT"
// }
// }

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.

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: Client

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

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

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

storage: Client

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

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.

void

// Log out the user
nhost.clearSession()
getUserSession(): Session | null;

Get the current session from storage. This method retrieves the authenticated user’s session information if one exists.

Session | null

The current session or null if no session exists

const session = nhost.getUserSession()
if (session) {
console.log('User is authenticated:', session.user.id)
} else {
console.log('No active session')
}
refreshSession(marginSeconds: number): Promise<Session | null>;

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.

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.

Promise<Session | null>

The new session or null if there is currently no session or if refresh fails

// 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)

Configuration options for creating an Nhost client

optional authUrl: string;

Complete base URL for the auth service (overrides subdomain/region)

optional configure: ClientConfigurationFn[];

Configuration functions to be applied to the client after initialization. These functions receive all clients and can attach middleware or perform other setup.

optional functionsUrl: string;

Complete base URL for the functions service (overrides subdomain/region)

optional graphqlUrl: string;

Complete base URL for the GraphQL service (overrides subdomain/region)

optional region: string;

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

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.

optional storageUrl: string;

Complete base URL for the storage service (overrides subdomain/region)

optional subdomain: string;

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


Configuration options for creating an Nhost client

optional authUrl: string;

Complete base URL for the auth service (overrides subdomain/region)

NhostClientOptions.authUrl

optional configure: ClientConfigurationFn[];

Configuration functions to be applied to the client after initialization. These functions receive all clients and can attach middleware or perform other setup.

NhostClientOptions.configure

optional functionsUrl: string;

Complete base URL for the functions service (overrides subdomain/region)

NhostClientOptions.functionsUrl

optional graphqlUrl: string;

Complete base URL for the GraphQL service (overrides subdomain/region)

NhostClientOptions.graphqlUrl

optional region: string;

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

NhostClientOptions.region

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.

NhostClientOptions.storage

optional storageUrl: string;

Complete base URL for the storage service (overrides subdomain/region)

NhostClientOptions.storageUrl

optional subdomain: string;

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

NhostClientOptions.subdomain

type ClientConfigurationFn = (clients: object) => void

Configuration function that receives all clients and can configure them (e.g., by attaching middleware, setting up interceptors, etc.)

ParameterType
clients{ auth: Client; functions: Client; graphql: Client; sessionStorage: SessionStorage; storage: Client; }
clients.authClient
clients.functionsClient
clients.graphqlClient
clients.sessionStorageSessionStorage
clients.storageClient

void

const withClientSideSessionMiddleware: ClientConfigurationFn

Built-in configuration for client-side applications. Includes automatic session refresh, token attachment, and session updates.


const withServerSideSessionMiddleware: ClientConfigurationFn

Built-in configuration for server-side applications. Includes token attachment and session updates, but NOT automatic session refresh to prevent race conditions in server contexts.

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.

ParameterTypeDescription
optionsNhostClientOptionsConfiguration options for the client

NhostClient

A configured Nhost client

// 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'
})
})
// Create client with additional custom middleware
const nhost = createClient({
subdomain: 'abcdefgh',
region: 'eu-central-1',
configure: [customLoggingMiddleware]
})

function createNhostClient(options: NhostClientOptions): NhostClient

Creates and configures a new Nhost client instance with custom configuration.

This is the main factory function for creating Nhost clients. It instantiates all service clients (auth, storage, graphql, functions) and applies the provided configuration functions to set up middleware and other customizations.

ParameterTypeDescription
optionsNhostClientOptionsConfiguration options for the client

NhostClient

A configured Nhost client

// Create a basic client with no middleware
const nhost = createNhostClient({
subdomain: 'abcdefgh',
region: 'eu-central-1',
configure: []
})
// Create a client with custom configuration
const nhost = createNhostClient({
subdomain: 'abcdefgh',
region: 'eu-central-1',
configure: [withClientSideSessionMiddleware, withChainFunctions([customLoggingMiddleware])]
})
// Create an admin client
const nhost = createNhostClient({
subdomain,
region,
configure: [
withAdminSession({
adminSecret: 'nhost-admin-secret',
role: 'user',
sessionVariables: {
'user-id': '54058C42-51F7-4B37-8B69-C89A841D2221'
}
})
]
})

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.

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

NhostClient

A configured Nhost client optimized for server-side usage

// 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')
}
}
})
}
// Example with additional custom middleware
const nhost = createServerClient({
region: process.env['NHOST_REGION'] || 'local',
subdomain: process.env['NHOST_SUBDOMAIN'] || 'local',
storage: myStorage,
configure: [customLoggingMiddleware]
})

function generateServiceUrl(
serviceType: 'auth' | 'storage' | 'graphql' | 'functions',
subdomain?: string,
region?: string,
customUrl?: string
): string

Generates a base URL for a Nhost service based on configuration

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

string

The base URL for the service


function withAdminSession(adminSession: AdminSessionOptions): ClientConfigurationFn

Configuration for admin clients with elevated privileges. Applies admin session middleware to storage, graphql, and functions clients only.

Security Warning: Never use this in client-side code. Admin secrets grant unrestricted access to your entire database.

ParameterTypeDescription
adminSessionAdminSessionOptionsAdmin session options including admin secret, role, and session variables

ClientConfigurationFn

Configuration function that sets up admin middleware