Skip to content

Commit 16437d6

Browse files
fix(remix): Get env variables in Cloudflare Pages context (clerk#2844) (clerk#2907)
(cherry picked from commit 9c34a75) * fix(clerk-js): Fix Remix + Cloudflare env variables Co-authored-by: arjunyel <arjunyel@users.noreply.github.com>
1 parent 73dd6f9 commit 16437d6

3 files changed

Lines changed: 33 additions & 6 deletions

File tree

.changeset/calm-humans-suffer.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---

.changeset/twenty-yaks-behave.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/remix': patch
3+
---
4+
5+
Correctly get environment variables inside Cloudflare Pages by accessing `context.cloudflare`

packages/remix/src/utils.ts

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,17 @@ export function assertValidClerkState(val: any): asserts val is ClerkState | und
2424
}
2525
}
2626

27+
type CloudflareEnv = { env: Record<string, string> };
28+
29+
// https://remix.run/blog/remix-vite-stable#cloudflare-pages-support
30+
const hasCloudflareProxyContext = (context: any): context is { cloudflare: CloudflareEnv } => {
31+
return !!context?.cloudflare?.env;
32+
};
33+
34+
const hasCloudflareContext = (context: any): context is CloudflareEnv => {
35+
return !!context?.env;
36+
};
37+
2738
/**
2839
*
2940
* 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
3344
*/
3445
export const getEnvVariable = (name: string, context: AppLoadContext | undefined): string => {
3546
// Node envs
36-
if (typeof process !== 'undefined') {
37-
return (process.env && process.env[name]) || '';
47+
if (typeof process !== 'undefined' && process.env && typeof process.env[name] === 'string') {
48+
return process.env[name] as string;
49+
}
50+
51+
// Remix + Cloudflare pages
52+
// if (typeof (context?.cloudflare as CloudflareEnv)?.env !== 'undefined') {
53+
if (hasCloudflareProxyContext(context)) {
54+
return context.cloudflare.env[name] || '';
3855
}
3956

40-
// Cloudflare pages
41-
if (typeof context !== 'undefined') {
42-
const contextEnv = context?.env as Record<string, string>;
57+
// Cloudflare
58+
if (hasCloudflareContext(context)) {
59+
return context.env[name] || '';
60+
}
4361

44-
return contextEnv[name] || (context[name] as string) || '';
62+
// Check whether the value exists in the context object directly
63+
if (context && typeof context[name] === 'string') {
64+
return context[name] as string;
4565
}
4666

4767
// Cloudflare workers

0 commit comments

Comments
 (0)