Skip to main content
Enhanced fetch implementation with middleware support. This module provides a middleware pattern for the Fetch API, allowing chain functions to be applied to requests and responses, such as authentication token refreshing, error handling, and request/response transformation. This is an advanced submodule of the Nhost SDK, primarily used internally but it is exposed for advanced use cases.

Classes

FetchError<T>

Error class for representing fetch operation failures. This class extends the standard Error to include additional information about failed requests, including the response body, status code, and headers. The error message is automatically extracted from common error response formats.

Extends

  • Error

Type Parameters

Type ParameterDefault typeDescription
TunknownThe type of the response body

Constructors

Constructor

new FetchError<T>(
   body: T,
   status: number,
   headers: Headers): FetchError<T>;
Creates a new FetchError instance
Parameters
ParameterTypeDescription
bodyTThe response body from the failed request
statusnumberThe HTTP status code
headersHeadersThe response headers
Returns
FetchError<T>
Overrides
Error.constructor

Properties

PropertyTypeDescription
bodyTThe original response body
headersHeadersResponse headers
statusnumberHTTP status code of the failed response

Interfaces

AdminSessionOptions

Configuration options for admin session middleware

Properties

adminSecret

adminSecret: string
Hasura admin secret for elevated permissions (sets x-hasura-admin-secret header)

role?

optional role: string;
Hasura role to use for the request (sets x-hasura-role header)

sessionVariables?

optional sessionVariables: Record<string, string>;
Additional Hasura session variables to attach to requests. Keys will be automatically prefixed with ‘x-hasura-’ if not already present.
Example
{
  'user-id': '123',
  'org-id': '456'
}
// Results in headers:
// x-hasura-user-id: 123
// x-hasura-org-id: 456

FetchResponse<T>

Interface representing a structured API response. This interface provides a consistent structure for responses across the SDK, offering access to the parsed response body along with status and headers.

Type Parameters

Type ParameterDescription
TThe type of the response body

Properties

body

body: T
The parsed response body

headers

headers: Headers
Response headers

status

status: number
HTTP status code of the response

Type Aliases

ChainFunction()

type ChainFunction = (next: FetchFunction) => FetchFunction
Type definition for a chain function (middleware). Takes a fetch-like function and returns another fetch-like function. Chain functions can be used to implement:
  • Authentication token handling
  • Error handling and retry logic
  • Request and response transformations
  • Logging and metrics

Parameters

ParameterType
nextFetchFunction

Returns

FetchFunction

FetchFunction()

type FetchFunction = (url: string, options?: RequestInit) => Promise<Response>
Type definition for a fetch-like function. Takes the same parameters as fetch and returns the same type. This allows middleware to intercept and modify requests and responses.

Parameters

ParameterType
urlstring
options?RequestInit

Returns

Promise<Response>

Functions

attachAccessTokenMiddleware()

function attachAccessTokenMiddleware(storage: SessionStorage): ChainFunction
Creates a fetch middleware that adds the Authorization header with the current access token. This middleware:
  1. Gets the current session from storage
  2. Adds the authorization header with the access token to outgoing requests
This middleware should be used after the refresh middleware in the chain to ensure the most recent token is used.

Parameters

ParameterTypeDescription
storageSessionStorageStorage implementation for retrieving session data

Returns

ChainFunction A middleware function that adds Authorization headers

createEnhancedFetch()

function createEnhancedFetch(chainFunctions: ChainFunction[]): FetchFunction
Creates an enhanced fetch function using a chain of middleware functions. The fetch chain executes in the order of the array, with each middleware wrapping the next one in the chain. This allows each middleware to intercept both the request (before calling next) and the response (after calling next).

Parameters

ParameterTypeDefault valueDescription
chainFunctionsChainFunction[][]Array of chain functions to apply in order

Returns

FetchFunction Enhanced fetch function with all middleware applied

Example

// Simple logging middleware
const loggingMiddleware: ChainFunction = (next) => {
  return async (url, options) => {
    console.log(`Request to ${url}`)
    const response = await next(url, options)
    console.log(`Response from ${url}: ${response.status}`)
    return response
  }
}

const enhancedFetch = createEnhancedFetch([loggingMiddleware])
const response = await enhancedFetch('https://api.example.com/data')

sessionRefreshMiddleware()

function sessionRefreshMiddleware(
  auth: Client,
  storage: SessionStorage,
  options?: object
): ChainFunction
Creates a fetch middleware that automatically refreshes authentication tokens. This middleware:
  1. Checks if the current token is about to expire
  2. If so, uses the refresh token to obtain a new access token
The middleware handles token refresh transparently, so the application doesn’t need to manually refresh tokens.

Parameters

ParameterTypeDescription
authClientAuth API client for token refresh operations
storageSessionStorageStorage implementation for persisting session data
options?{ marginSeconds?: number; }Configuration options for token refresh behavior
options.marginSeconds?numberNumber of seconds before token expiration to trigger a refresh, default is 60 seconds

Returns

ChainFunction A middleware function that can be used in the fetch chain

updateSessionFromResponseMiddleware()

function updateSessionFromResponseMiddleware(storage: SessionStorage): ChainFunction
Creates a fetch middleware that automatically extracts and stores session data from API responses. This middleware:
  1. Monitors responses from authentication-related endpoints
  2. Extracts session information when present
  3. Stores the session in the provided storage implementation
  4. Handles session removal on sign-out
This ensures that session data is always up-to-date in storage after operations that create or invalidate sessions.

Parameters

ParameterTypeDescription
storageSessionStorageStorage implementation for persisting session data

Returns

ChainFunction A middleware function that can be used in the fetch chain

withAdminSessionMiddleware()

function withAdminSessionMiddleware(options: AdminSessionOptions): ChainFunction
Creates a fetch middleware that attaches the Hasura admin secret and optional session variables to requests. This middleware:
  1. Sets the x-hasura-admin-secret header, which grants full admin access to Hasura
  2. Optionally sets the x-hasura-role header if a role is provided
  3. Optionally sets additional x-hasura-* headers for custom session variables
Security Warning: Never use this middleware in client-side code or expose the admin secret to end users. Admin secrets grant unrestricted access to your entire database. This should only be used in trusted server-side environments. The middleware preserves request-specific headers when they conflict with the admin session configuration.

Parameters

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

Returns

ChainFunction A middleware function that can be used in the fetch chain

Example

// Create middleware with admin secret only
const adminMiddleware = withAdminSessionMiddleware({
  adminSecret: process.env.NHOST_ADMIN_SECRET
})

// Create middleware with admin secret and role
const adminUserMiddleware = withAdminSessionMiddleware({
  adminSecret: process.env.NHOST_ADMIN_SECRET,
  role: 'user'
})

// Create middleware with admin secret, role, and custom session variables
const fullMiddleware = withAdminSessionMiddleware({
  adminSecret: process.env.NHOST_ADMIN_SECRET,
  role: 'user',
  sessionVariables: {
    'user-id': '123',
    'org-id': '456'
  }
})

// Use with createCustomClient for an admin client
const adminClient = createCustomClient({
  subdomain: 'myproject',
  region: 'eu-central-1',
  chainFunctions: [adminMiddleware]
})

withHeadersMiddleware()

function withHeadersMiddleware(defaultHeaders: HeadersInit): ChainFunction
Creates a fetch middleware that attaches default headers to requests. This middleware:
  1. Merges default headers with request-specific headers
  2. Preserves request-specific headers when they conflict with defaults
The middleware ensures consistent headers across requests while allowing individual requests to override defaults as needed.

Parameters

ParameterTypeDescription
defaultHeadersHeadersInitDefault headers to attach to all requests

Returns

ChainFunction A middleware function that can be used in the fetch chain

withRoleMiddleware()

function withRoleMiddleware(role: string): ChainFunction
Creates a fetch middleware that sets the Hasura role header. This middleware sets the x-hasura-role header for all requests, allowing you to specify which role’s permissions should be used. This works with authenticated sessions where the user has access to the specified role. Unlike withAdminSessionMiddleware, this does not bypass permission rules but instead uses the permission rules defined for the specified role. The middleware preserves request-specific headers when they conflict with the role configuration.

Parameters

ParameterTypeDescription
rolestringThe Hasura role to use for requests

Returns

ChainFunction A middleware function that can be used in the fetch chain

Example

// Use with createClient to default all requests to a specific role
const nhost = createClient({
  subdomain: 'myproject',
  region: 'eu-central-1',
  chainFunctions: [withRoleMiddleware('moderator')]
})

// Use with createServerClient for server-side requests
const serverNhost = createServerClient({
  subdomain: 'myproject',
  region: 'eu-central-1',
  storage: myServerStorage,
  chainFunctions: [withRoleMiddleware('moderator')]
})