Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] env is not accessible writing inline #231

Open
j4tmr opened this issue Jan 8, 2025 · 7 comments
Open

[BUG] env is not accessible writing inline #231

j4tmr opened this issue Jan 8, 2025 · 7 comments
Labels
documentation Improvements or additions to documentation question Further information is requested

Comments

@j4tmr
Copy link

j4tmr commented Jan 8, 2025

Describe the bug

export const api = createApiClient({ endpoint: process.env.API_URL! });
not able to get process.env.API_URL

export const createApi = () => createApiClient({ endpoint: process.env.API_URL! });
able to get

Steps to reproduce

simple as write

Expected behavior

get env both

@opennextjs/cloudflare version

0.3.4

Wrangler version

3.100.0

next info output

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.6.0: Mon Jul 29 21:14:30 PDT 2024; root:xnu-10063.141.2~1/RELEASE_ARM64_T6000
  Available memory (MB): 65536
  Available CPU cores: 10
Binaries:
  Node: 20.10.0
  npm: 10.9.2
  Yarn: 1.22.19
  pnpm: N/A
Relevant Packages:
  next: 15.1.4 // Latest available version is detected (15.1.4).
  eslint-config-next: 15.1.4
  react: 19.0.0
  react-dom: 19.0.0
  typescript: 5.7.2
Next.js Config:
  output: N/A

Additional context

No response

@j4tmr j4tmr added bug Something isn't working triage labels Jan 8, 2025
@vicb
Copy link
Contributor

vicb commented Jan 8, 2025

Do you expect env to be the cloudflare bindings (the env parameter to the fetch handler)?

If so:

  • The cloudflare "environment variables" are accessible directly on process, i.e. process.env.API_URL
  • The bindings (KV, ...) are available via getCloudflareContext().env

However it would be better to add your variable to a NextJs .env* file.
When doing so, it will also be available at process.env.API_URL.
This is a better practice as process.API_URL will also be available in your dev workflow (pnpm run build / next dev)

Hope this helps.

edit: fixed process -> process.env (see next comment)

@j4tmr
Copy link
Author

j4tmr commented Jan 9, 2025

@vicb , thanks for your reply! I still think adding to .env* is the best approach because there are times when we may want to switch back to using Next.js locally rather than in Cloudflare Worker. I added API_URL="http://localhost:3999" to .env, and it works well with a pure Next.js project.

I believe in your last sentence, you meant process.env.API_URL, as Next.js by default accesses environment variables through process.env. The issue I encountered is that when I write export const api = createApiClient({ endpoint: process.env.API_URL! });, after compilation, process.env.API_URL is not correctly accessed. Only the process.env in dynamic methods seems to work properly. I think this is primarily a compilation issue, specifically related to this command: "build:worker": "opennextjs-cloudflare".

@vicb
Copy link
Contributor

vicb commented Jan 9, 2025

I believe in your last sentence, you meant process.env.API_URL

You are right, sorry for the confusion, I'll update my original message

The issue I encountered is that when I write export const api = createApiClient({ endpoint: process.env.API_URL! });, after compilation, process.env.API_URL is not correctly accessed.

It would help if you can create a minimal repro in a GH repository and attach it here.
One thing I can think of is that you access the variable at top level but it wouldn't be initialized before the first request is handled.

@j4tmr
Copy link
Author

j4tmr commented Jan 9, 2025

@vicb One thing I can think of is that you access the variable at top level but it wouldn't be initialized before the first request is handled. i think this is the case. cause nextjs has its own build mechanism to replace the process.env.API_URL or init it at start before first request.

@vicb
Copy link
Contributor

vicb commented Jan 9, 2025

If that's the case, one way you could solve this is by changing

export const api = createApiClient({ endpoint: process.env.API_URL! });

for

export function getApi() {
  return createApiClient({ endpoint: process.env.API_URL! });
}

That way process.env.API_URL will only be evaluated in a request context when it has been initialized.

@vicb vicb added question Further information is requested and removed bug Something isn't working triage labels Jan 13, 2025
@vicb vicb added the documentation Improvements or additions to documentation label Jan 20, 2025
@JonasDoesThings
Copy link

This is also problematic since it prevents using specific route-wrappers.
For example using upstash's API-route wrapper (docs: https://upstash.com/docs/qstash/quickstarts/vercel-nextjs, code: https://github.com/upstash/qstash-js/blob/main/platforms/nextjs.ts#L147) like this:

import { verifySignatureAppRouter } from "@upstash/qstash/nextjs"

// 👇 Verify that this messages comes from QStash
export const POST = verifySignatureAppRouter(async (req: Request) => {
  const body = await req.json()
  const { imageId } = body as { imageId: string }

  // Image processing logic, i.e. using sharp

  return new Response(`Image with id "${imageId}" processed successfully.`)
})

does not work, due to the required env vars not being retrieved at runtime.

@vicb
Copy link
Contributor

vicb commented Jan 29, 2025

@JonasDoesThings Something along those lines should work:

export const POST = async (req: Request, params?: unknown) => {
  // process.env is populated at that point
  const handler = lazilyCreateHandler();
  return await handler(req, params);
});

function lazilyCreateHandler() {
  return verifySignatureAppRouter(async (req: Request) => {
    const body = await req.json()
    const { imageId } = body as { imageId: string }

    // Image processing logic, i.e. using sharp

    return new Response(`Image with id "${imageId}" processed successfully.`)
  });  
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation question Further information is requested
Development

No branches or pull requests

3 participants