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
Section titled “Import”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// automaticallyawait nhost.auth.signUpEmailPassword({ email, password})
// upload a couple of filesconst 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 filesconst 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 functionconst funcResp = await nhost.functions.post('/helloworld', { message: 'Hello, World!'})console.log(JSON.stringify(funcResp.body, null, 2))// {// "message": "Hello, World!"// }Creating an admin client
Section titled “Creating an admin client”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 filesconst 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"// }// }Interfaces
Section titled “Interfaces”NhostClient
Section titled “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
Section titled “Properties”auth: ClientAuthentication client providing methods for user sign-in, sign-up, and session management. Use this client to handle all authentication-related operations.
functions
Section titled “functions”functions: ClientFunctions client providing methods for invoking serverless functions. Use this client to call your custom serverless functions deployed to Nhost.
graphql
Section titled “graphql”graphql: ClientGraphQL 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
Section titled “sessionStorage”sessionStorage: SessionStorageStorage implementation used for persisting session information. This handles saving, retrieving, and managing authentication sessions across requests.
storage
Section titled “storage”storage: ClientStorage client providing methods for file operations (upload, download, delete). Use this client to manage files in your Nhost storage.
Methods
Section titled “Methods”clearSession()
Section titled “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
Section titled “Returns”void
Example
Section titled “Example”// Log out the usernhost.clearSession()getUserSession()
Section titled “getUserSession()”getUserSession(): Session | null;Get the current session from storage. This method retrieves the authenticated user’s session information if one exists.
Returns
Section titled “Returns”Session | null
The current session or null if no session exists
Example
Section titled “Example”const session = nhost.getUserSession()if (session) { console.log('User is authenticated:', session.user.id)} else { console.log('No active session')}refreshSession()
Section titled “refreshSession()”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.
Parameters
Section titled “Parameters”| Parameter | Type | Default value | Description |
|---|---|---|---|
marginSeconds | number | 60 | The 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
Section titled “Returns”Promise<Session | null>
The new session or null if there is currently no session or if refresh fails
Example
Section titled “Example”// Refresh token if it's about to expire in the next 5 minutesconst refreshedSession = await nhost.refreshSession(300)
// Force refresh regardless of current token expirationconst forcedRefresh = await nhost.refreshSession(0)NhostClientOptions
Section titled “NhostClientOptions”Configuration options for creating an Nhost client
Extended by
Section titled “Extended by”Properties
Section titled “Properties”authUrl?
Section titled “authUrl?”optional authUrl: string;Complete base URL for the auth service (overrides subdomain/region)
configure?
Section titled “configure?”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.
functionsUrl?
Section titled “functionsUrl?”optional functionsUrl: string;Complete base URL for the functions service (overrides subdomain/region)
graphqlUrl?
Section titled “graphqlUrl?”optional graphqlUrl: string;Complete base URL for the GraphQL service (overrides subdomain/region)
region?
Section titled “region?”optional region: string;Nhost region (e.g., ‘eu-central-1’). Used to construct the base URL for services for the Nhost cloud.
storage?
Section titled “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?
Section titled “storageUrl?”optional storageUrl: string;Complete base URL for the storage service (overrides subdomain/region)
subdomain?
Section titled “subdomain?”optional subdomain: string;Nhost project subdomain (e.g., ‘abcdefgh’). Used to construct the base URL for services for the Nhost cloud.
NhostServerClientOptions
Section titled “NhostServerClientOptions”Configuration options for creating an Nhost client
Extends
Section titled “Extends”Properties
Section titled “Properties”authUrl?
Section titled “authUrl?”optional authUrl: string;Complete base URL for the auth service (overrides subdomain/region)
Inherited from
Section titled “Inherited from”configure?
Section titled “configure?”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.
Inherited from
Section titled “Inherited from”functionsUrl?
Section titled “functionsUrl?”optional functionsUrl: string;Complete base URL for the functions service (overrides subdomain/region)
Inherited from
Section titled “Inherited from”NhostClientOptions.functionsUrl
graphqlUrl?
Section titled “graphqlUrl?”optional graphqlUrl: string;Complete base URL for the GraphQL service (overrides subdomain/region)
Inherited from
Section titled “Inherited from”region?
Section titled “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
Section titled “Inherited from”storage
Section titled “storage”storage: SessionStorageBackendStorage 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
Section titled “Overrides”storageUrl?
Section titled “storageUrl?”optional storageUrl: string;Complete base URL for the storage service (overrides subdomain/region)
Inherited from
Section titled “Inherited from”subdomain?
Section titled “subdomain?”optional subdomain: string;Nhost project subdomain (e.g., ‘abcdefgh’). Used to construct the base URL for services for the Nhost cloud.
Inherited from
Section titled “Inherited from”Type Aliases
Section titled “Type Aliases”ClientConfigurationFn()
Section titled “ClientConfigurationFn()”type ClientConfigurationFn = (clients: object) => voidConfiguration function that receives all clients and can configure them (e.g., by attaching middleware, setting up interceptors, etc.)
Parameters
Section titled “Parameters”| Parameter | Type |
|---|---|
clients | { auth: Client; functions: Client; graphql: Client; sessionStorage: SessionStorage; storage: Client; } |
clients.auth | Client |
clients.functions | Client |
clients.graphql | Client |
clients.sessionStorage | SessionStorage |
clients.storage | Client |
Returns
Section titled “Returns”void
Variables
Section titled “Variables”withClientSideSessionMiddleware
Section titled “withClientSideSessionMiddleware”const withClientSideSessionMiddleware: ClientConfigurationFnBuilt-in configuration for client-side applications. Includes automatic session refresh, token attachment, and session updates.
withServerSideSessionMiddleware
Section titled “withServerSideSessionMiddleware”const withServerSideSessionMiddleware: ClientConfigurationFnBuilt-in configuration for server-side applications. Includes token attachment and session updates, but NOT automatic session refresh to prevent race conditions in server contexts.
Functions
Section titled “Functions”createClient()
Section titled “createClient()”function createClient(options: NhostClientOptions): NhostClientCreates 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
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
options | NhostClientOptions | Configuration options for the client |
Returns
Section titled “Returns”A configured Nhost client
Example
Section titled “Example”// Create client using Nhost cloud default URLsconst nhost = createClient({ subdomain: 'abcdefgh', region: 'eu-central-1'})
// Create client with custom service URLsconst 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 sessionimport { 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 middlewareconst nhost = createClient({ subdomain: 'abcdefgh', region: 'eu-central-1', configure: [customLoggingMiddleware]})createNhostClient()
Section titled “createNhostClient()”function createNhostClient(options: NhostClientOptions): NhostClientCreates 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.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
options | NhostClientOptions | Configuration options for the client |
Returns
Section titled “Returns”A configured Nhost client
Example
Section titled “Example”// Create a basic client with no middlewareconst nhost = createNhostClient({ subdomain: 'abcdefgh', region: 'eu-central-1', configure: []})
// Create a client with custom configurationconst nhost = createNhostClient({ subdomain: 'abcdefgh', region: 'eu-central-1', configure: [withClientSideSessionMiddleware, withChainFunctions([customLoggingMiddleware])]})
// Create an admin clientconst nhost = createNhostClient({ subdomain, region, configure: [ withAdminSession({ adminSecret: 'nhost-admin-secret', role: 'user', sessionVariables: { 'user-id': '54058C42-51F7-4B37-8B69-C89A841D2221' } }) ]})createServerClient()
Section titled “createServerClient()”function createServerClient(options: NhostServerClientOptions): NhostClientCreates 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
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
options | NhostServerClientOptions | Configuration options for the server client (requires storage implementation) |
Returns
Section titled “Returns”A configured Nhost client optimized for server-side usage
Example
Section titled “Example”// Example with cookie storage for Next.js API route or server componentimport { 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 middlewareconst 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 middlewareconst nhost = createServerClient({ region: process.env['NHOST_REGION'] || 'local', subdomain: process.env['NHOST_SUBDOMAIN'] || 'local', storage: myStorage, configure: [customLoggingMiddleware]})generateServiceUrl()
Section titled “generateServiceUrl()”function generateServiceUrl( serviceType: 'auth' | 'storage' | 'graphql' | 'functions', subdomain?: string, region?: string, customUrl?: string): stringGenerates a base URL for a Nhost service based on configuration
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
serviceType | "auth" | "storage" | "graphql" | "functions" | Type of service (auth, storage, graphql, functions) |
subdomain? | string | Nhost project subdomain |
region? | string | Nhost region |
customUrl? | string | Custom URL override if provided |
Returns
Section titled “Returns”string
The base URL for the service
withAdminSession()
Section titled “withAdminSession()”function withAdminSession(adminSession: AdminSessionOptions): ClientConfigurationFnConfiguration 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.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
adminSession | AdminSessionOptions | Admin session options including admin secret, role, and session variables |
Returns
Section titled “Returns”Configuration function that sets up admin middleware