Skip to content

Commit 70e08cf

Browse files
authored
SSR related improvements for RC client SDK. (#8699)
SSR related improvements for RC client SDK. * Exposes an initialFetchResponse arg that pre-hydrates the client SDK state * Adds an argument that allows setting an alternate template ID to fetch from * Splits storage impls into a simple in-memory version that can be run in SSR contexts * Adds some basic tests for the API functions, which were previously untested
1 parent b3e68ca commit 70e08cf

22 files changed

+647
-214
lines changed

.changeset/flat-plums-hope.md

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@firebase/remote-config': minor
3+
'firebase': minor
4+
---
5+
6+
Adds support for initial state hydration (from SSR contexts)

common/api-review/remote-config.api.md

+20-1
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,22 @@ export function fetchAndActivate(remoteConfig: RemoteConfig): Promise<boolean>;
2424
// @public
2525
export function fetchConfig(remoteConfig: RemoteConfig): Promise<void>;
2626

27+
// @public
28+
export interface FetchResponse {
29+
config?: FirebaseRemoteConfigObject;
30+
eTag?: string;
31+
status: number;
32+
}
33+
2734
// @public
2835
export type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle';
2936

37+
// @public
38+
export interface FirebaseRemoteConfigObject {
39+
// (undocumented)
40+
[key: string]: string;
41+
}
42+
3043
// @public
3144
export function getAll(remoteConfig: RemoteConfig): Record<string, Value>;
3245

@@ -37,7 +50,7 @@ export function getBoolean(remoteConfig: RemoteConfig, key: string): boolean;
3750
export function getNumber(remoteConfig: RemoteConfig, key: string): number;
3851

3952
// @public (undocumented)
40-
export function getRemoteConfig(app?: FirebaseApp): RemoteConfig;
53+
export function getRemoteConfig(app?: FirebaseApp, options?: RemoteConfigOptions): RemoteConfig;
4154

4255
// @public
4356
export function getString(remoteConfig: RemoteConfig, key: string): string;
@@ -62,6 +75,12 @@ export interface RemoteConfig {
6275
settings: RemoteConfigSettings;
6376
}
6477

78+
// @public
79+
export interface RemoteConfigOptions {
80+
initialFetchResponse?: FetchResponse;
81+
templateId?: string;
82+
}
83+
6584
// @public
6685
export interface RemoteConfigSettings {
6786
fetchTimeoutMillis: number;

docs-devsite/_toc.yaml

+6
Original file line numberDiff line numberDiff line change
@@ -430,8 +430,14 @@ toc:
430430
section:
431431
- title: CustomSignals
432432
path: /docs/reference/js/remote-config.customsignals.md
433+
- title: FetchResponse
434+
path: /docs/reference/js/remote-config.fetchresponse.md
435+
- title: FirebaseRemoteConfigObject
436+
path: /docs/reference/js/remote-config.firebaseremoteconfigobject.md
433437
- title: RemoteConfig
434438
path: /docs/reference/js/remote-config.remoteconfig.md
439+
- title: RemoteConfigOptions
440+
path: /docs/reference/js/remote-config.remoteconfigoptions.md
435441
- title: RemoteConfigSettings
436442
path: /docs/reference/js/remote-config.remoteconfigsettings.md
437443
- title: Value
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
Project: /docs/reference/js/_project.yaml
2+
Book: /docs/reference/_book.yaml
3+
page_type: reference
4+
5+
{% comment %}
6+
DO NOT EDIT THIS FILE!
7+
This is generated by the JS SDK team, and any local changes will be
8+
overwritten. Changes should be made in the source code at
9+
https://github.com/firebase/firebase-js-sdk
10+
{% endcomment %}
11+
12+
# FetchResponse interface
13+
Defines a successful response (200 or 304).
14+
15+
<p>Modeled after the native `Response` interface, but simplified for Remote Config's use case.
16+
17+
<b>Signature:</b>
18+
19+
```typescript
20+
export interface FetchResponse
21+
```
22+
23+
## Properties
24+
25+
| Property | Type | Description |
26+
| --- | --- | --- |
27+
| [config](./remote-config.fetchresponse.md#fetchresponseconfig) | [FirebaseRemoteConfigObject](./remote-config.firebaseremoteconfigobject.md#firebaseremoteconfigobject_interface) | Defines the map of parameters returned as "entries" in the fetch response body.<p>Only defined for 200 responses. |
28+
| [eTag](./remote-config.fetchresponse.md#fetchresponseetag) | string | Defines the ETag response header value.<p>Only defined for 200 and 304 responses. |
29+
| [status](./remote-config.fetchresponse.md#fetchresponsestatus) | number | The HTTP status, which is useful for differentiating success responses with data from those without.<p>The Remote Config client is modeled after the native <code>Fetch</code> interface, so HTTP status is first-class.<p>Disambiguation: the fetch response returns a legacy "state" value that is redundant with the HTTP status code. The former is normalized into the latter. |
30+
31+
## FetchResponse.config
32+
33+
Defines the map of parameters returned as "entries" in the fetch response body.
34+
35+
<p>Only defined for 200 responses.
36+
37+
<b>Signature:</b>
38+
39+
```typescript
40+
config?: FirebaseRemoteConfigObject;
41+
```
42+
43+
## FetchResponse.eTag
44+
45+
Defines the ETag response header value.
46+
47+
<p>Only defined for 200 and 304 responses.
48+
49+
<b>Signature:</b>
50+
51+
```typescript
52+
eTag?: string;
53+
```
54+
55+
## FetchResponse.status
56+
57+
The HTTP status, which is useful for differentiating success responses with data from those without.
58+
59+
<p>The Remote Config client is modeled after the native `Fetch` interface, so HTTP status is first-class.
60+
61+
<p>Disambiguation: the fetch response returns a legacy "state" value that is redundant with the HTTP status code. The former is normalized into the latter.
62+
63+
<b>Signature:</b>
64+
65+
```typescript
66+
status: number;
67+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Project: /docs/reference/js/_project.yaml
2+
Book: /docs/reference/_book.yaml
3+
page_type: reference
4+
5+
{% comment %}
6+
DO NOT EDIT THIS FILE!
7+
This is generated by the JS SDK team, and any local changes will be
8+
overwritten. Changes should be made in the source code at
9+
https://github.com/firebase/firebase-js-sdk
10+
{% endcomment %}
11+
12+
# FirebaseRemoteConfigObject interface
13+
Defines a self-descriptive reference for config key-value pairs.
14+
15+
<b>Signature:</b>
16+
17+
```typescript
18+
export interface FirebaseRemoteConfigObject
19+
```

docs-devsite/remote-config.md

+7-3
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ The Firebase Remote Config Web SDK. This SDK does not work in a Node.js environm
1717
| Function | Description |
1818
| --- | --- |
1919
| <b>function(app, ...)</b> |
20-
| [getRemoteConfig(app)](./remote-config.md#getremoteconfig_cf608e1) | |
20+
| [getRemoteConfig(app, options)](./remote-config.md#getremoteconfig_61d368f) | |
2121
| <b>function(remoteConfig, ...)</b> |
2222
| [activate(remoteConfig)](./remote-config.md#activate_722a192) | Makes the last fetched config available to the getters. |
2323
| [ensureInitialized(remoteConfig)](./remote-config.md#ensureinitialized_722a192) | Ensures the last activated config are available to the getters. |
@@ -38,7 +38,10 @@ The Firebase Remote Config Web SDK. This SDK does not work in a Node.js environm
3838
| Interface | Description |
3939
| --- | --- |
4040
| [CustomSignals](./remote-config.customsignals.md#customsignals_interface) | Defines the type for representing custom signals and their values.<p>The values in CustomSignals must be one of the following types:<ul> <li><code>string</code> <li><code>number</code> <li><code>null</code> </ul> |
41+
| [FetchResponse](./remote-config.fetchresponse.md#fetchresponse_interface) | Defines a successful response (200 or 304).<p>Modeled after the native <code>Response</code> interface, but simplified for Remote Config's use case. |
42+
| [FirebaseRemoteConfigObject](./remote-config.firebaseremoteconfigobject.md#firebaseremoteconfigobject_interface) | Defines a self-descriptive reference for config key-value pairs. |
4143
| [RemoteConfig](./remote-config.remoteconfig.md#remoteconfig_interface) | The Firebase Remote Config service interface. |
44+
| [RemoteConfigOptions](./remote-config.remoteconfigoptions.md#remoteconfigoptions_interface) | Options for Remote Config initialization. |
4245
| [RemoteConfigSettings](./remote-config.remoteconfigsettings.md#remoteconfigsettings_interface) | Defines configuration options for the Remote Config SDK. |
4346
| [Value](./remote-config.value.md#value_interface) | Wraps a value with metadata and type-safe getters. |
4447

@@ -52,19 +55,20 @@ The Firebase Remote Config Web SDK. This SDK does not work in a Node.js environm
5255

5356
## function(app, ...)
5457

55-
### getRemoteConfig(app) {:#getremoteconfig_cf608e1}
58+
### getRemoteConfig(app, options) {:#getremoteconfig_61d368f}
5659

5760
<b>Signature:</b>
5861

5962
```typescript
60-
export declare function getRemoteConfig(app?: FirebaseApp): RemoteConfig;
63+
export declare function getRemoteConfig(app?: FirebaseApp, options?: RemoteConfigOptions): RemoteConfig;
6164
```
6265

6366
#### Parameters
6467

6568
| Parameter | Type | Description |
6669
| --- | --- | --- |
6770
| app | [FirebaseApp](./app.firebaseapp.md#firebaseapp_interface) | The [FirebaseApp](./app.firebaseapp.md#firebaseapp_interface) instance. |
71+
| options | [RemoteConfigOptions](./remote-config.remoteconfigoptions.md#remoteconfigoptions_interface) | Optional. The [RemoteConfigOptions](./remote-config.remoteconfigoptions.md#remoteconfigoptions_interface) with which to instantiate the Remote Config instance. |
6872

6973
<b>Returns:</b>
7074

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
Project: /docs/reference/js/_project.yaml
2+
Book: /docs/reference/_book.yaml
3+
page_type: reference
4+
5+
{% comment %}
6+
DO NOT EDIT THIS FILE!
7+
This is generated by the JS SDK team, and any local changes will be
8+
overwritten. Changes should be made in the source code at
9+
https://github.com/firebase/firebase-js-sdk
10+
{% endcomment %}
11+
12+
# RemoteConfigOptions interface
13+
Options for Remote Config initialization.
14+
15+
<b>Signature:</b>
16+
17+
```typescript
18+
export interface RemoteConfigOptions
19+
```
20+
21+
## Properties
22+
23+
| Property | Type | Description |
24+
| --- | --- | --- |
25+
| [initialFetchResponse](./remote-config.remoteconfigoptions.md#remoteconfigoptionsinitialfetchresponse) | [FetchResponse](./remote-config.fetchresponse.md#fetchresponse_interface) | Hydrates the state with an initial fetch response. |
26+
| [templateId](./remote-config.remoteconfigoptions.md#remoteconfigoptionstemplateid) | string | The ID of the template to use. If not provided, defaults to "firebase". |
27+
28+
## RemoteConfigOptions.initialFetchResponse
29+
30+
Hydrates the state with an initial fetch response.
31+
32+
<b>Signature:</b>
33+
34+
```typescript
35+
initialFetchResponse?: FetchResponse;
36+
```
37+
38+
## RemoteConfigOptions.templateId
39+
40+
The ID of the template to use. If not provided, defaults to "firebase".
41+
42+
<b>Signature:</b>
43+
44+
```typescript
45+
templateId?: string;
46+
```

packages/remote-config/src/api.ts

+38-5
Original file line numberDiff line numberDiff line change
@@ -16,35 +16,68 @@
1616
*/
1717

1818
import { _getProvider, FirebaseApp, getApp } from '@firebase/app';
19+
import { deepEqual, getModularInstance } from '@firebase/util';
1920
import {
2021
CustomSignals,
2122
LogLevel as RemoteConfigLogLevel,
2223
RemoteConfig,
23-
Value
24+
Value,
25+
RemoteConfigOptions
2426
} from './public_types';
2527
import { RemoteConfigAbortSignal } from './client/remote_config_fetch_client';
2628
import {
2729
RC_COMPONENT_NAME,
2830
RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH,
2931
RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH
3032
} from './constants';
31-
import { ErrorCode, hasErrorCode } from './errors';
33+
import { ERROR_FACTORY, ErrorCode, hasErrorCode } from './errors';
3234
import { RemoteConfig as RemoteConfigImpl } from './remote_config';
3335
import { Value as ValueImpl } from './value';
3436
import { LogLevel as FirebaseLogLevel } from '@firebase/logger';
35-
import { getModularInstance } from '@firebase/util';
3637

3738
/**
3839
*
3940
* @param app - The {@link @firebase/app#FirebaseApp} instance.
41+
* @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the
42+
* Remote Config instance.
4043
* @returns A {@link RemoteConfig} instance.
4144
*
4245
* @public
4346
*/
44-
export function getRemoteConfig(app: FirebaseApp = getApp()): RemoteConfig {
47+
export function getRemoteConfig(
48+
app: FirebaseApp = getApp(),
49+
options: RemoteConfigOptions = {}
50+
): RemoteConfig {
4551
app = getModularInstance(app);
4652
const rcProvider = _getProvider(app, RC_COMPONENT_NAME);
47-
return rcProvider.getImmediate();
53+
if (rcProvider.isInitialized()) {
54+
const initialOptions = rcProvider.getOptions() as RemoteConfigOptions;
55+
if (deepEqual(initialOptions, options)) {
56+
return rcProvider.getImmediate();
57+
}
58+
throw ERROR_FACTORY.create(ErrorCode.ALREADY_INITIALIZED);
59+
}
60+
rcProvider.initialize({ options });
61+
const rc = rcProvider.getImmediate() as RemoteConfigImpl;
62+
63+
if (options.initialFetchResponse) {
64+
// We use these initial writes as the initialization promise since they will hydrate the same
65+
// fields that `storageCache.loadFromStorage` would set.
66+
rc._initializePromise = Promise.all([
67+
rc._storage.setLastSuccessfulFetchResponse(options.initialFetchResponse),
68+
rc._storage.setActiveConfigEtag(options.initialFetchResponse?.eTag || ''),
69+
rc._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),
70+
rc._storageCache.setLastFetchStatus('success'),
71+
rc._storageCache.setActiveConfig(
72+
options.initialFetchResponse?.config || {}
73+
)
74+
]).then();
75+
// The `storageCache` methods above set their in-memory fields synchronously, so it's
76+
// safe to declare our initialization complete at this point.
77+
rc._isInitializationComplete = true;
78+
}
79+
80+
return rc;
4881
}
4982

5083
/**

packages/remote-config/src/client/caching_client.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
*/
1717

1818
import { StorageCache } from '../storage/storage_cache';
19+
import { FetchResponse } from '../public_types';
1920
import {
20-
FetchResponse,
2121
RemoteConfigFetchClient,
2222
FetchRequest
2323
} from './remote_config_fetch_client';

packages/remote-config/src/client/remote_config_fetch_client.ts

+1-45
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
* limitations under the License.
1616
*/
1717

18-
import { CustomSignals } from '../public_types';
18+
import { CustomSignals, FetchResponse } from '../public_types';
1919

2020
/**
2121
* Defines a client, as in https://en.wikipedia.org/wiki/Client%E2%80%93server_model, for the
@@ -36,13 +36,6 @@ export interface RemoteConfigFetchClient {
3636
fetch(request: FetchRequest): Promise<FetchResponse>;
3737
}
3838

39-
/**
40-
* Defines a self-descriptive reference for config key-value pairs.
41-
*/
42-
export interface FirebaseRemoteConfigObject {
43-
[key: string]: string;
44-
}
45-
4639
/**
4740
* Shims a minimal AbortSignal.
4841
*
@@ -108,40 +101,3 @@ export interface FetchRequest {
108101
*/
109102
customSignals?: CustomSignals;
110103
}
111-
112-
/**
113-
* Defines a successful response (200 or 304).
114-
*
115-
* <p>Modeled after the native {@link Response} interface, but simplified for Remote Config's
116-
* use case.
117-
*/
118-
export interface FetchResponse {
119-
/**
120-
* The HTTP status, which is useful for differentiating success responses with data from
121-
* those without.
122-
*
123-
* <p>{@link RemoteConfigClient} is modeled after the native {@link GlobalFetch} interface, so
124-
* HTTP status is first-class.
125-
*
126-
* <p>Disambiguation: the fetch response returns a legacy "state" value that is redundant with the
127-
* HTTP status code. The former is normalized into the latter.
128-
*/
129-
status: number;
130-
131-
/**
132-
* Defines the ETag response header value.
133-
*
134-
* <p>Only defined for 200 and 304 responses.
135-
*/
136-
eTag?: string;
137-
138-
/**
139-
* Defines the map of parameters returned as "entries" in the fetch response body.
140-
*
141-
* <p>Only defined for 200 responses.
142-
*/
143-
config?: FirebaseRemoteConfigObject;
144-
145-
// Note: we're not extracting experiment metadata until
146-
// ABT and Analytics have Web SDKs.
147-
}

0 commit comments

Comments
 (0)