Skip to content
New issue

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

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

Already on GitHub? # to your account

Docs: Add section for @next/env package #64908

Merged
merged 6 commits into from
Apr 23, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,52 @@ export async function GET() {

</AppOnly>

### Loading Environment Variables with `@next/env`

If you need to load environment variables outside the Next.js runtime, such as in a root config file for an ORM or Test Runner, you can use the `@next/env` package.

This package is used internally by Next.js to load environment variables from `.env*` files, and can be used in your own code to load environment variables:

```bash
npm install @next/env
```

```tsx filename="envConfig.ts" switcher
import { loadEnvConfig } from '@next/env'

const projectDir = process.cwd()
loadEnvConfig(projectDir)
```

```jsx filename="envConfig.js" switcher
import { loadEnvConfig } from '@next/env'

const projectDir = process.cwd()
loadEnvConfig(projectDir)
```

Then, you can import the configuration where needed. For example:

```tsx filename="orm.config.ts" switcher
import 'envConfig.js'

export default defineConfig({
dbCredentials: {
connectionString: process.env.DATABASE_URL!,
},
})
```

```jsx filename="orm.config.js" switcher
import 'envConfig.js'

export default defineConfig({
dbCredentials: {
connectionString: process.env.DATABASE_URL,
},
})
```

### Referencing Other Variables

Next.js will automatically expand variables that use `$` to reference other variables e.g. `$VARIABLE` inside of your `.env*` files. This allows you to reference other secrets. For example:
Expand Down