CreateRelayEnvironment
Environment. Instead of wiring Network, RecordSource, Store,
retries, token refresh, session redirect and a subscription socket by hand, you pass a few options and get
back Environment and StorageHandler. Only url is required.When to use
- a React app uses Relay and needs auth, retries, caching or subscriptions;
- you want one place that configures the app's GraphQL backend.
- you need custom network interceptors or several schemas — assemble the
Environmentwithrelay-runtime; - the app does not use Relay.
Usage
import { CreateRelayEnvironment } from '@apollion-dsi/relay/setupRelayEnvironment';
export const { Environment, StorageHandler } = new CreateRelayEnvironment({
url: 'https://api.example.com/graphql/',
authUrl: 'https://api.example.com/auth/',
socket: 'wss://api.example.com/graphql/',
useAuthorization: true,
useRetries: true,
useSubscription: true,
redirectOnError: true,
loginRoute: '/login',
});Mount Environment once with EnvironmentProvider.
Authentication
authMode: 'bearer'(default) — readssessionTokenfrom storage and sendsAuthorization: Bearer <token>on GraphQL requests and on the${authUrl}user/meprobe whenuseAuthorizationis on. The header is omitted onloginRouteonly when you passedloginRoute. The default'/'does not strip the header on the home page. Store tokens withStorageHandler.setTokens({ sessionToken, refreshToken }).authMode: 'cookie'— the session is an httpOnly cookie. No token is read and no header is sent;credentials: 'include'(the default in this mode) attaches the cookie, including on the socket handshake. On an authentication error the client sends aPOSTtoauthUrl. The token is never placed in the URL.
graphqlErrorPolicy is 'legacy' (default) or 'payload'.
legacy— any GraphQLerrorsarray probes the session and is pushed withsink.error. Partialdatais dropped.payload— a body that hasdatais pushed withsink.nextso Relay normalizes it, errors included. A body with nodataissink.error. The session is probed and storage is cleared only when an errorstatus_codeis inauthenticationErrors. A transportTypeErrordoes not clear storage.
Subscriptions and polling
The first subscription opens a graphql-ws client. When useAuthorization is on and authMode is not
'cookie', connectionParams sends { Authorization: 'Bearer <token>' } on every connect, including
reconnect. The client is disposed when the last subscriber leaves.
subscriptionClient sets the client's retry, keep-alive and event policy. connection — returned next to
Environment — is the socket's state and handles (reconnect, terminate, dispose). A subscription that
ends reaches Relay as a SubscriptionError with the server's code. See
liveConnection.
@client_polling(interval: Int!) belongs on a query and is declared in your schema. The compiler writes
metadata.live.polling_interval in milliseconds. This package polls that interval and sets force on those
ticks so the response cache is not reused. If cacheConfig.poll is already set, this package does not poll
again; Relay's Network.create does. This is not a server live-query protocol. A GraphQL @live that only
sets metadata.live.config_id is not a push channel. Resolver @live uses the liveState helpers.
Requests
Unsubscribing a query aborts the fetch. useRetries retries queries only, not mutations. With useCache,
QueryResponseCache stores a body only when it has data and no errors.
A Relay UploadableMap ({ [key]: File | Blob }) is multipart, mapped to variables.<key>. The legacy
{ files, path(i) } shape still works. Multipart operations include name and operationName.
fetch-multipart-graphql reads multipart/mixed incremental JSON for @defer and @stream. It does not
implement uploads.
redirectUser chooses ? or & from the destination URL, applies encodeURIComponent to the return path,
omits that path when it already equals the destination, and does nothing when there is no DOM.
Persisted queries
With usePersistedQueries: true the client sends only the hash relay-compiler stamps at build time. Set
persistConfig in the compiler config; without it the first request throws. Rename doc_id with
persistedOperationField. Refuse an unknown hash with 200 and { errors }: a 4xx is absorbed by the
retry layer.
Transport | Payload |
|---|---|
Query or mutation (HTTP) | { name, doc_id, variables }, no query key |
Upload (multipart) | operations { name, doc_id, variables, operationName } |
Subscription ( graphql-ws) | { operationName, query: '', variables, extensions: { doc_id } } |
Options
Option | Type | Default | Description |
|---|---|---|---|
url | string | required | GraphQL HTTP endpoint. |
authUrl | string | — | Auth endpoint; required with useAuthorization. |
socket | string | — | WebSocket endpoint; required with useSubscription. |
authMode | 'bearer' | 'cookie' | 'bearer' | Token header or httpOnly cookie session. |
useAuthorization | boolean | false | Sends Authorization in bearer mode. |
credentials | RequestCredentials | 'include' in cookie mode | Forwarded to GraphQL and refresh requests. |
sessionCheckUrl | string | false | depends on authMode | Session probe URL; false disables it. |
storageType | 'localStorage' | 'cookie' | 'localStorage' | Where bearer mode stores tokens. |
sessionStorageProp | string | 'USER_SESSION_TOKEN' | Session token key. |
refreshStorageProp | string | 'USER_REFRESH_TOKEN' | Refresh token key. |
redirectOnError | boolean | false | Redirects on an auth error. |
loginRoute | string | '/' | Redirect target. Strips the header only if you pass it. |
authenticationErrors | number[] | [401, 403] | Status codes that count as an auth failure. |
graphqlErrorPolicy | 'legacy' | 'payload' | 'legacy' | Drop partial data, or forward data to Relay. |
useRetries | boolean | false | Retries failed queries. Mutations are not retried. |
retries | number[] | 1, 2, 3, 5, 8, 13, 21, 34 s | Delays between attempts, in ms. |
retryWhen | number[] | [503, 504, 521, 522, 524] | Status codes that trigger a retry. |
timeout | number | 15 minutes | Per-request timeout, in ms. |
useCache | boolean | false | Caches bodies that have data and no errors. |
cacheTime | number | 8 minutes | Cache TTL, in ms. |
cacheSize | number | 250 | Maximum cached queries. |
useSubscription | boolean | false | Subscriptions over graphql-ws. |
subscriptionClient | SubscriptionClientOptions | graphql-ws defaults | Retry, keep-alive and event policy of the socket. |
useDebug | boolean | false | Logs retries in development. |
partner | string | — | Sent as the X-Partner header. |
usePersistedQueries | boolean | false | Sends only the build-time operation hash. |
persistedOperationField | string | 'doc_id' | Request field that carries the hash. |
initialRecords | RelayInitialRecords | empty store | Seeds the store with app-owned records. |
initialRecords seeds the store at creation. Read the records back with the same fragments as server data,
through a client schema extension. The type follows relay-runtime's RecordSource constructor.