Replies: 2 comments
-
If it is still actual question, I saw several times and personally do it myself. Using import { createJiti } from 'jiti';
/**
* Import env files to validate at build time. Use jiti so we can load .ts files in here.
*
* @type {import('./env.ts')}
*/
const { env } = await createJiti(import.meta.url).import('./env'); And for env validation personally prefer using |
Beta Was this translation helpful? Give feedback.
-
Unfortunately, using instrumentation is not reliable for this kind of thing - as you discovered it does not always execute and things just get more complicated in all the permutations of static/dynamic/output/runtimes/etc... There really should be a general hooks system but alas there is not. Next also does not give us any hooks related to env var loading, so the only option I have discovered is to override the internal This is precisely what I've done to build the Next.js integration for a general env var management tool - https://varlock.dev It gives you the validation logic you are looking for, and a whole lot more :) It also is trying to be a universal system applicable to every project :) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
I thought it would be a good idea to ensure that environment variables are properly set. I'm using zod for validation and put the logic into a separate module, so I can use that instead of accessing
process.env
directly.So far, so good, but now I'd like to get feedback about missing or invalid variables as early possible, in all three commands:
next dev
,next build
andnext start
. For startup code, instrumentation seems to be the expected choice:But it doesn't work very well for my case. It's not executed at all during
next build
, andnext start
just catches the error and then says "Ready" instead of existing. Sure, I could useprocess.exit(1)
instead, but still the build wouldn't have validation (and it needs some API keys from the environment to build static pages).Including the check (or the import of the checking module) in a page doesn't work either, it's only checked on demand in
next dev
and executed very late innext build
.That last option seems to be integrating the check in
next.config.ts
. Here I can either throw or exit and that prevents all three commands from running. But I'm a bit afraid that it might run before the framework has fully set up the environment.So - is it safe to use
next.config.ts
for validation? Or is there a better way?Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions