-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathenv-script.tsx
More file actions
74 lines (66 loc) · 2.38 KB
/
Copy pathenv-script.tsx
File metadata and controls
74 lines (66 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// XXX: Blocked by https://github.com/vercel/next.js/pull/58129
// import { headers } from 'next/headers';
import Script, { type ScriptProps } from 'next/script';
import { type FC } from 'react';
import { type NonceConfig } from '../typings/nonce';
import { type ProcessEnv } from '../typings/process-env';
import { PUBLIC_ENV_KEY } from './constants';
type EnvScriptProps = {
env: ProcessEnv;
nonce?: string | NonceConfig;
disableNextScript?: boolean;
nextScriptProps?: ScriptProps;
};
/**
* Sets the provided environment variables in the browser. If an nonce is
* available, it will be set on the script tag.
*
* Usage:
* ```ts
* <head>
* <EnvScript env={{ NODE_ENV: 'test', API_URL: 'http://localhost:3000' }} />
* </head>
* ```
*/
export const EnvScript: FC<EnvScriptProps> = ({
env,
nonce,
disableNextScript = false,
nextScriptProps = { strategy: 'beforeInteractive' },
}) => {
let nonceString: string | undefined;
// XXX: Blocked by https://github.com/vercel/next.js/pull/58129
// if (typeof nonce === 'object' && nonce !== null) {
// // It's strongly recommended to set a nonce on your script tags.
// nonceString = headers().get(nonce.headerKey) ?? undefined;
// }
if (typeof nonce === 'string') {
nonceString = nonce;
}
const innerHTML = {
__html: `window['${PUBLIC_ENV_KEY}'] = ${JSON.stringify(env)}`,
};
// You can opt to use a regular "<script>" tag instead of Next.js' Script Component.
// Note: When using Sentry, sentry.client.config.ts might run after the Next.js <Script> component, even when the strategy is "beforeInteractive"
// This results in the runtime environments being undefined and the Sentry client config initialized without the correct configuration.
if (disableNextScript) {
// Set suppressHydrationWarning on the vanilla script tag if nonce is being used, as React will
// throw a ssr hydration error otherwise. This is because the browser removes the nonce from the
// DOM before the hydration check takes place, leading to a mismatch. This can be safely ignored.
return (
<script
suppressHydrationWarning={!!nonceString}
nonce={nonceString}
dangerouslySetInnerHTML={innerHTML}
/>
);
}
// Use Next.js Script Component by default
return (
<Script
{...nextScriptProps}
nonce={nonceString}
dangerouslySetInnerHTML={innerHTML}
/>
);
};