Skip to content

Fetch

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.

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.

  • Error
Type ParameterDefault typeDescription
TunknownThe type of the response body
new FetchError<T>(
body: T,
status: number,
headers: Headers): FetchError<T>;

Creates a new FetchError instance

ParameterTypeDescription
bodyTThe response body from the failed request
statusnumberThe HTTP status code
headersHeadersThe response headers

FetchError<T>

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

Configuration options for admin session middleware

adminSecret: string

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

optional role: string;

Hasura role to use for the request (sets x-hasura-role header)

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.

{
'user-id': '123',
'org-id': '456'
}
// Results in headers:
// x-hasura-user-id: 123
// x-hasura-org-id: 456

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 ParameterDescription
TThe type of the response body
body: T

The parsed response body

headers: Headers

Response headers

status: number

HTTP status code of the response

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
ParameterType
nextFetchFunction

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.

ParameterType
urlstring
options?RequestInit

Promise<Response>

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.

ParameterTypeDescription
storageSessionStorageStorage implementation for retrieving session data

ChainFunction

A middleware function that adds Authorization headers


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

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

FetchFunction

Enhanced fetch function with all middleware applied

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

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.

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

ChainFunction

A middleware function that can be used in the fetch chain


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.

ParameterTypeDescription
storageSessionStorageStorage implementation for persisting session data

ChainFunction

A middleware function that can be used in the fetch chain


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.

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

ChainFunction

A middleware function that can be used in the fetch chain

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

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.

ParameterTypeDescription
defaultHeadersHeadersInitDefault headers to attach to all requests

ChainFunction

A middleware function that can be used in the fetch chain


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.

ParameterTypeDescription
rolestringThe Hasura role to use for requests

ChainFunction

A middleware function that can be used in the fetch chain

// 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')]
})