Test suites often run without a full set of environment variables. A unit test for a utility function does not need DATABASE_URL or JWT_SECRET to be present, but next-safe-env would ordinarily crash the process if those required fields are missing. The skipValidation option lets you bypass field-level validation so your tests can import env without needing every variable populated.
Using skipValidation
Pass skipValidation: process.env.NODE_ENV === 'test' to opt out of validation whenever your test runner sets NODE_ENV=test:
// src/env.ts
export const env = createEnv({
server: { DATABASE_URL: url(), JWT_SECRET: str().min(32) },
client: {},
runtimeEnv: {
DATABASE_URL: process.env.DATABASE_URL,
JWT_SECRET: process.env.JWT_SECRET,
},
skipValidation: process.env.NODE_ENV === 'test',
})
What skipValidation does
When skipValidation is true:
beforeValidate (the adapter’s prefix-enforcement hook) is skipped entirely.
- Field-level validation is skipped - required fields will not throw if they are
undefined, and coercions such as num() and bool() are not applied.
afterValidate still runs - the adapter’s key-stripping logic (for example, removing server vars in a browser context) is applied as normal.
- The raw string values from
runtimeEnv are returned in the typed shape with no coercion. A field typed as number may hold a string at runtime when validation is skipped.
Never set skipValidation: true in production or in CI steps that are meant to validate your deployment environment. In those contexts, you want next-safe-env to catch missing or malformed variables before they reach your users.
For more granular control, you can drive skipValidation from a dedicated boolean environment variable instead of NODE_ENV:skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',
This lets you enable skipping in specific test scripts without coupling it to NODE_ENV, which some teams reserve for other purposes.
Using a separate .env.test file with Next.js
Next.js supports environment-specific .env files out of the box. Create a .env.test file at the root of your project with only the variables your tests actually need:
# .env.test
NODE_ENV=test
DATABASE_URL=postgresql://localhost:5432/myapp_test
Next.js automatically loads .env.test when NODE_ENV is test, so your test suite picks up these values without any extra configuration. Variables not listed in .env.test will be undefined, which is safe when skipValidation is enabled.