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.
Classes
Section titled “Classes”FetchError
Section titled “FetchError”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
Section titled “Extends”Error
Type Parameters
Section titled “Type Parameters”| Type Parameter | Default type | Description |
|---|---|---|
T | unknown | The type of the response body |
Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new FetchError<T>( body: T, status: number, headers: Headers): FetchError<T>;Creates a new FetchError instance
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
body | T | The response body from the failed request |
status | number | The HTTP status code |
headers | Headers | The response headers |
Returns
Section titled “Returns”FetchError<T>
Overrides
Section titled “Overrides”Error.constructorProperties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
body | T | The original response body |
headers | Headers | Response headers |
status | number | HTTP status code of the failed response |
Interfaces
Section titled “Interfaces”AdminSessionOptions
Section titled “AdminSessionOptions”Configuration options for admin session middleware
Properties
Section titled “Properties”adminSecret
Section titled “adminSecret”adminSecret: stringHasura 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)
sessionVariables?
Section titled “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
Section titled “Example”{ 'user-id': '123', 'org-id': '456'}// Results in headers:// x-hasura-user-id: 123// x-hasura-org-id: 456FetchResponse
Section titled “FetchResponse”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
Section titled “Type Parameters”| Type Parameter | Description |
|---|---|
T | The type of the response body |
Properties
Section titled “Properties”body: TThe parsed response body
headers
Section titled “headers”headers: HeadersResponse headers
status
Section titled “status”status: numberHTTP status code of the response
Type Aliases
Section titled “Type Aliases”ChainFunction()
Section titled “ChainFunction()”type ChainFunction = (next: FetchFunction) => FetchFunctionType 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
Section titled “Parameters”| Parameter | Type |
|---|---|
next | FetchFunction |
Returns
Section titled “Returns”FetchFunction()
Section titled “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
Section titled “Parameters”| Parameter | Type |
|---|---|
url | string |
options? | RequestInit |
Returns
Section titled “Returns”Promise<Response>
Functions
Section titled “Functions”attachAccessTokenMiddleware()
Section titled “attachAccessTokenMiddleware()”function attachAccessTokenMiddleware(storage: SessionStorage): ChainFunctionCreates a fetch middleware that adds the Authorization header with the current access token.
This middleware:
- Gets the current session from storage
- 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
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
storage | SessionStorage | Storage implementation for retrieving session data |
Returns
Section titled “Returns”A middleware function that adds Authorization headers
createEnhancedFetch()
Section titled “createEnhancedFetch()”function createEnhancedFetch(chainFunctions: ChainFunction[]): FetchFunctionCreates 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
Section titled “Parameters”| Parameter | Type | Default value | Description |
|---|---|---|---|
chainFunctions | ChainFunction[] | [] | Array of chain functions to apply in order |
Returns
Section titled “Returns”Enhanced fetch function with all middleware applied
Example
Section titled “Example”// Simple logging middlewareconst 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()
Section titled “sessionRefreshMiddleware()”function sessionRefreshMiddleware( auth: Client, storage: SessionStorage, options?: object): ChainFunctionCreates a fetch middleware that automatically refreshes authentication tokens.
This middleware:
- Checks if the current token is about to expire
- 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
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
auth | Client | Auth API client for token refresh operations |
storage | SessionStorage | Storage implementation for persisting session data |
options? | { marginSeconds?: number; } | Configuration options for token refresh behavior |
options.marginSeconds? | number | Number of seconds before token expiration to trigger a refresh, default is 60 seconds |
Returns
Section titled “Returns”A middleware function that can be used in the fetch chain
updateSessionFromResponseMiddleware()
Section titled “updateSessionFromResponseMiddleware()”function updateSessionFromResponseMiddleware(storage: SessionStorage): ChainFunctionCreates a fetch middleware that automatically extracts and stores session data from API responses.
This middleware:
- Monitors responses from authentication-related endpoints
- Extracts session information when present
- Stores the session in the provided storage implementation
- 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
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
storage | SessionStorage | Storage implementation for persisting session data |
Returns
Section titled “Returns”A middleware function that can be used in the fetch chain
withAdminSessionMiddleware()
Section titled “withAdminSessionMiddleware()”function withAdminSessionMiddleware(options: AdminSessionOptions): ChainFunctionCreates a fetch middleware that attaches the Hasura admin secret and optional session variables to requests.
This middleware:
- Sets the x-hasura-admin-secret header, which grants full admin access to Hasura
- Optionally sets the x-hasura-role header if a role is provided
- 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
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
options | AdminSessionOptions | Admin session options including admin secret, role, and session variables |
Returns
Section titled “Returns”A middleware function that can be used in the fetch chain
Example
Section titled “Example”// Create middleware with admin secret onlyconst adminMiddleware = withAdminSessionMiddleware({ adminSecret: process.env.NHOST_ADMIN_SECRET})
// Create middleware with admin secret and roleconst adminUserMiddleware = withAdminSessionMiddleware({ adminSecret: process.env.NHOST_ADMIN_SECRET, role: 'user'})
// Create middleware with admin secret, role, and custom session variablesconst fullMiddleware = withAdminSessionMiddleware({ adminSecret: process.env.NHOST_ADMIN_SECRET, role: 'user', sessionVariables: { 'user-id': '123', 'org-id': '456' }})
// Use with createCustomClient for an admin clientconst adminClient = createCustomClient({ subdomain: 'myproject', region: 'eu-central-1', chainFunctions: [adminMiddleware]})withHeadersMiddleware()
Section titled “withHeadersMiddleware()”function withHeadersMiddleware(defaultHeaders: HeadersInit): ChainFunctionCreates a fetch middleware that attaches default headers to requests.
This middleware:
- Merges default headers with request-specific headers
- 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
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
defaultHeaders | HeadersInit | Default headers to attach to all requests |
Returns
Section titled “Returns”A middleware function that can be used in the fetch chain
withRoleMiddleware()
Section titled “withRoleMiddleware()”function withRoleMiddleware(role: string): ChainFunctionCreates 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
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
role | string | The Hasura role to use for requests |
Returns
Section titled “Returns”A middleware function that can be used in the fetch chain
Example
Section titled “Example”// Use with createClient to default all requests to a specific roleconst nhost = createClient({ subdomain: 'myproject', region: 'eu-central-1', chainFunctions: [withRoleMiddleware('moderator')]})
// Use with createServerClient for server-side requestsconst serverNhost = createServerClient({ subdomain: 'myproject', region: 'eu-central-1', storage: myServerStorage, chainFunctions: [withRoleMiddleware('moderator')]})