From 25c2d6a9d455510950d99ae163624497b4c0b8fe Mon Sep 17 00:00:00 2001 From: arjunyel Date: Fri, 1 Mar 2024 04:24:23 -0600 Subject: [PATCH] fix(remix): Get env variables in Cloudflare Pages context (#2844) (cherry picked from commit 9c34a756efa68d430e2231547576a20a6d9e6dc0) * fix(clerk-js): Fix Remix + Cloudflare env variables --- .changeset/calm-humans-suffer.md | 2 ++ .changeset/twenty-yaks-behave.md | 5 +++++ packages/remix/src/utils.ts | 32 ++++++++++++++++++++++++++------ 3 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 .changeset/calm-humans-suffer.md create mode 100644 .changeset/twenty-yaks-behave.md diff --git a/.changeset/calm-humans-suffer.md b/.changeset/calm-humans-suffer.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/calm-humans-suffer.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/.changeset/twenty-yaks-behave.md b/.changeset/twenty-yaks-behave.md new file mode 100644 index 00000000000..28405911152 --- /dev/null +++ b/.changeset/twenty-yaks-behave.md @@ -0,0 +1,5 @@ +--- +'@clerk/remix': patch +--- + +Correctly get environment variables inside Cloudflare Pages by accessing `context.cloudflare` diff --git a/packages/remix/src/utils.ts b/packages/remix/src/utils.ts index d5f19dc27d8..3f7ff32ac37 100644 --- a/packages/remix/src/utils.ts +++ b/packages/remix/src/utils.ts @@ -24,6 +24,17 @@ export function assertValidClerkState(val: any): asserts val is ClerkState | und } } +type CloudflareEnv = { env: Record }; + +// https://remix.run/blog/remix-vite-stable#cloudflare-pages-support +const hasCloudflareProxyContext = (context: any): context is { cloudflare: CloudflareEnv } => { + return !!context?.cloudflare?.env; +}; + +const hasCloudflareContext = (context: any): context is CloudflareEnv => { + return !!context?.env; +}; + /** * * Utility function to get env variables across Node and Edge runtimes. @@ -33,15 +44,24 @@ export function assertValidClerkState(val: any): asserts val is ClerkState | und */ export const getEnvVariable = (name: string, context: AppLoadContext | undefined): string => { // Node envs - if (typeof process !== 'undefined') { - return (process.env && process.env[name]) || ''; + if (typeof process !== 'undefined' && process.env && typeof process.env[name] === 'string') { + return process.env[name] as string; + } + + // Remix + Cloudflare pages + // if (typeof (context?.cloudflare as CloudflareEnv)?.env !== 'undefined') { + if (hasCloudflareProxyContext(context)) { + return context.cloudflare.env[name] || ''; } - // Cloudflare pages - if (typeof context !== 'undefined') { - const contextEnv = context?.env as Record; + // Cloudflare + if (hasCloudflareContext(context)) { + return context.env[name] || ''; + } - return contextEnv[name] || (context[name] as string) || ''; + // Check whether the value exists in the context object directly + if (context && typeof context[name] === 'string') { + return context[name] as string; } // Cloudflare workers