Skip to content

Commit

Permalink
fix: ensure .env.local files are automatically loaded in bin scripts …
Browse files Browse the repository at this point in the history
…and within importConfig
  • Loading branch information
AlessioGr committed Jun 3, 2024
1 parent c3589de commit 184fbb2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
24 changes: 13 additions & 11 deletions packages/payload/src/bin/loadEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@ import fs from 'fs'
import path from 'path'

/**
* Try to find user's .env and load it
* Try to find user's env file and load it. Supports both .env and .env.local
*/
export function loadEnv() {
const envPath = findUp.sync('.env')
const envFiles = ['.env', '.env.local']

if (envPath) {
dotenv.config({ path: envPath })
} else {
const cwdPath = path.resolve(process.cwd(), '.env')
if (fs.existsSync(cwdPath)) {
dotenv.config({
path: cwdPath,
})
export function loadEnv() {
for (const file of envFiles) {
const filePath = findUp.sync(file)
if (filePath) {
dotenv.config({ path: filePath })
} else {
// If the file is not found via findUp, check the current working directory
const cwdPath = path.resolve(process.cwd(), file)
if (fs.existsSync(cwdPath)) {
dotenv.config({ path: cwdPath })
}
}
}
}
3 changes: 3 additions & 0 deletions packages/payload/src/utilities/importWithoutClientFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import path from 'path'

import type { SanitizedConfig } from '../config/types.js'

import { loadEnv } from '../bin/loadEnv.js'

const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)

Expand All @@ -20,6 +22,7 @@ export const importWithoutClientFiles = async <T = unknown>(filePath: string) =>
* Resolve and load Payload config from either a relative or absolute path
*/
export const importConfig = async (configPath: string) => {
loadEnv() // loadConfig would usually be run outside of next. This means they will not get next's automatic env loading here. In order to not force them to install dotenv and set it up manually, we can load the env for them here
const isAbsolutePath = path.isAbsolute(configPath)
if (isAbsolutePath) {
const config = await importWithoutClientFiles<{ default: Promise<SanitizedConfig> }>(configPath)
Expand Down

0 comments on commit 184fbb2

Please sign in to comment.