vitest icon indicating copy to clipboard operation
vitest copied to clipboard

vite-node should have different behavior with env vars than vite

Open ethanjdiamond opened this issue 2 years ago • 1 comments

Clear and concise description of the problem

In Vite's Env variables and modes documentation, there's a section on how Vite filters env variables that doesn't start with a specified prefix. This is what it says:

To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.

While that makes sense and is helpful when building a web bundle, it doesn't make as much sense for vite-node's use cases. In particular I have two use cases where it's highly inconvenient:

  • I'm running .ts scripts using vite-node via a hashbang in script mode (#!/usr/bin/env vite-node --script) that use child_process to run terminal commands. The PATH env var is getting filtered since it's not prefixed with VITE_, which makes running any terminal commands pretty much a no go.
  • I'm starting my express server using vite-node, and passing the port it should start on as an env var, and prefixing is inconvenient. Server-side is a safe environment for secrets.

Suggested solution

It'd be really helpful if vite-node followed how Next.js handles env var safety and didn't require a prefix in node environments. In Next, anything prefixed with NEXT_PUBLIC_ will be exposed to the browser, but there's no such restriction for the server.

Alternative

I considered potentially having a setting in vite.config.ts for vite-node that would allow you to set whether you needed a prefix for not, but in my project I use vite both to build my web app and as a script runner, so it'd be a little annoying to need two config files. I'd prefer vite-node to just allow through all env vars.

Additional context

No response

Validations

ethanjdiamond avatar Apr 26 '24 07:04 ethanjdiamond

I thought it should, but just verified that's not the case currently on vite-node. https://stackblitz.com/edit/github-pjqhpg?file=repro.ts

On Vitest, there is a few tricks (such as https://github.com/vitest-dev/vitest/pull/714) to make import.meta.env works mostly same as process.env, so this is probably working there, but something is missing for vite-node alone usage.

I thought you could at least use envPrefix: "", but Vite doesn't allow passing in such config as they assume its dangerous for web bundle use cases.

hi-ogawa avatar Apr 26 '24 09:04 hi-ogawa