Unverified Commit fafa16f3 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Bundle env configs in serverless mode (#13406)

As discussed this adds bundling of `.env` files in `serverless` mode so that the environment values are also available when deploying with this target

closes: https://github.com/zeit/next.js/issues/13332
parent 235b3bef
...@@ -8,6 +8,7 @@ import { normalizePagePath } from '../next-server/server/normalize-page-path' ...@@ -8,6 +8,7 @@ import { normalizePagePath } from '../next-server/server/normalize-page-path'
import { warn } from './output/log' import { warn } from './output/log'
import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader' import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader'
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader' import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import { LoadedEnvFiles } from '../lib/load-env-config'
type PagesMapping = { type PagesMapping = {
[page: string]: string [page: string]: string
...@@ -66,7 +67,8 @@ export function createEntrypoints( ...@@ -66,7 +67,8 @@ export function createEntrypoints(
target: 'server' | 'serverless' | 'experimental-serverless-trace', target: 'server' | 'serverless' | 'experimental-serverless-trace',
buildId: string, buildId: string,
previewMode: __ApiPreviewProps, previewMode: __ApiPreviewProps,
config: any config: any,
loadedEnvFiles: LoadedEnvFiles
): Entrypoints { ): Entrypoints {
const client: WebpackEntrypoints = {} const client: WebpackEntrypoints = {}
const server: WebpackEntrypoints = {} const server: WebpackEntrypoints = {}
...@@ -92,6 +94,7 @@ export function createEntrypoints( ...@@ -92,6 +94,7 @@ export function createEntrypoints(
}) })
: '', : '',
previewProps: JSON.stringify(previewMode), previewProps: JSON.stringify(previewMode),
loadedEnvFiles: JSON.stringify(loadedEnvFiles),
} }
Object.keys(pages).forEach((page) => { Object.keys(pages).forEach((page) => {
......
...@@ -106,7 +106,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -106,7 +106,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
} }
// attempt to load global env values so they are available in next.config.js // attempt to load global env values so they are available in next.config.js
loadEnvConfig(dir) const { loadedEnvFiles } = loadEnvConfig(dir)
const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf) const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const { target } = config const { target } = config
...@@ -217,7 +217,8 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -217,7 +217,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
target, target,
buildId, buildId,
previewProps, previewProps,
config config,
loadedEnvFiles
) )
const pageKeys = Object.keys(mappedPages) const pageKeys = Object.keys(mappedPages)
const conflictingPublicFiles: string[] = [] const conflictingPublicFiles: string[] = []
......
...@@ -26,6 +26,7 @@ export type ServerlessLoaderQuery = { ...@@ -26,6 +26,7 @@ export type ServerlessLoaderQuery = {
basePath: string basePath: string
runtimeConfig: string runtimeConfig: string
previewProps: string previewProps: string
loadedEnvFiles: string
} }
const nextServerlessLoader: loader.Loader = function () { const nextServerlessLoader: loader.Loader = function () {
...@@ -43,6 +44,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -43,6 +44,7 @@ const nextServerlessLoader: loader.Loader = function () {
basePath, basePath,
runtimeConfig, runtimeConfig,
previewProps, previewProps,
loadedEnvFiles,
}: ServerlessLoaderQuery = }: ServerlessLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
...@@ -60,6 +62,11 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -60,6 +62,11 @@ const nextServerlessLoader: loader.Loader = function () {
JSON.parse(previewProps) as __ApiPreviewProps JSON.parse(previewProps) as __ApiPreviewProps
) )
const envLoading = `
const { processEnv } = require('next/dist/lib/load-env-config')
processEnv(${loadedEnvFiles})
`
const runtimeConfigImports = runtimeConfig const runtimeConfigImports = runtimeConfig
? ` ? `
const { setConfig } = require('next/config') const { setConfig } = require('next/config')
...@@ -141,6 +148,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -141,6 +148,7 @@ const nextServerlessLoader: loader.Loader = function () {
import onError from 'next-plugin-loader?middleware=on-error-server!' import onError from 'next-plugin-loader?middleware=on-error-server!'
import 'next/dist/next-server/server/node-polyfill-fetch' import 'next/dist/next-server/server/node-polyfill-fetch'
${envLoading}
${runtimeConfigImports} ${runtimeConfigImports}
${ ${
/* /*
...@@ -207,6 +215,7 @@ const nextServerlessLoader: loader.Loader = function () { ...@@ -207,6 +215,7 @@ const nextServerlessLoader: loader.Loader = function () {
import onError from 'next-plugin-loader?middleware=on-error-server!' import onError from 'next-plugin-loader?middleware=on-error-server!'
import 'next/dist/next-server/server/node-polyfill-fetch' import 'next/dist/next-server/server/node-polyfill-fetch'
${envLoading}
${runtimeConfigImports} ${runtimeConfigImports}
${ ${
// this needs to be called first so its available for any other imports // this needs to be called first so its available for any other imports
......
...@@ -5,13 +5,61 @@ import dotenvExpand from 'next/dist/compiled/dotenv-expand' ...@@ -5,13 +5,61 @@ import dotenvExpand from 'next/dist/compiled/dotenv-expand'
import dotenv, { DotenvConfigOutput } from 'next/dist/compiled/dotenv' import dotenv, { DotenvConfigOutput } from 'next/dist/compiled/dotenv'
export type Env = { [key: string]: string } export type Env = { [key: string]: string }
export type LoadedEnvFiles = Array<{
path: string
contents: string
}>
let combinedEnv: Env | undefined = undefined let combinedEnv: Env | undefined = undefined
let loadedEnvFiles: LoadedEnvFiles = []
export function loadEnvConfig(dir: string, dev?: boolean): Env | false { export function processEnv(loadedEnvFiles: LoadedEnvFiles, dir?: string) {
// don't reload env if we already have since this breaks escaped // don't reload env if we already have since this breaks escaped
// environment values e.g. \$ENV_FILE_KEY // environment values e.g. \$ENV_FILE_KEY
if (combinedEnv) return combinedEnv if (
combinedEnv ||
process.env.__NEXT_PROCESSED_ENV ||
!loadedEnvFiles.length
) {
return process.env as Env
}
// flag that we processed the environment values in case a serverless
// function is re-used or we are running in `next start` mode
process.env.__NEXT_PROCESSED_ENV = 'true'
for (const envFile of loadedEnvFiles) {
try {
let result: DotenvConfigOutput = {}
result.parsed = dotenv.parse(envFile.contents)
result = dotenvExpand(result)
if (result.parsed) {
log.info(`Loaded env from ${path.join(dir || '', envFile.path)}`)
}
Object.assign(process.env, result.parsed)
} catch (err) {
log.error(
`Failed to load env from ${path.join(dir || '', envFile.path)}`,
err
)
}
}
return process.env as Env
}
export function loadEnvConfig(
dir: string,
dev?: boolean
): {
combinedEnv: Env
loadedEnvFiles: LoadedEnvFiles
} {
// don't reload env if we already have since this breaks escaped
// environment values e.g. \$ENV_FILE_KEY
if (combinedEnv) return { combinedEnv, loadedEnvFiles }
const isTest = process.env.NODE_ENV === 'test' const isTest = process.env.NODE_ENV === 'test'
const mode = isTest ? 'test' : dev ? 'development' : 'production' const mode = isTest ? 'test' : dev ? 'development' : 'production'
...@@ -25,10 +73,6 @@ export function loadEnvConfig(dir: string, dev?: boolean): Env | false { ...@@ -25,10 +73,6 @@ export function loadEnvConfig(dir: string, dev?: boolean): Env | false {
'.env', '.env',
].filter(Boolean) as string[] ].filter(Boolean) as string[]
combinedEnv = {
...(process.env as any),
} as Env
for (const envFile of dotenvFiles) { for (const envFile of dotenvFiles) {
// only load .env if the user provided has an env config file // only load .env if the user provided has an env config file
const dotEnvPath = path.join(dir, envFile) const dotEnvPath = path.join(dir, envFile)
...@@ -42,32 +86,16 @@ export function loadEnvConfig(dir: string, dev?: boolean): Env | false { ...@@ -42,32 +86,16 @@ export function loadEnvConfig(dir: string, dev?: boolean): Env | false {
} }
const contents = fs.readFileSync(dotEnvPath, 'utf8') const contents = fs.readFileSync(dotEnvPath, 'utf8')
let result: DotenvConfigOutput = {} loadedEnvFiles.push({
result.parsed = dotenv.parse(contents) path: envFile,
contents,
result = dotenvExpand(result) })
if (result.parsed) {
log.info(`Loaded env from ${dotEnvPath}`)
}
Object.assign(combinedEnv, result.parsed)
} catch (err) { } catch (err) {
if (err.code !== 'ENOENT') { if (err.code !== 'ENOENT') {
log.error(`Failed to load env from ${envFile}`, err) log.error(`Failed to load env from ${envFile}`, err)
} }
} }
} }
combinedEnv = processEnv(loadedEnvFiles, dir)
// load global env values prefixed with `NEXT_PUBLIC_` to process.env return { combinedEnv, loadedEnvFiles }
for (const key of Object.keys(combinedEnv)) {
if (
key.startsWith('NEXT_PUBLIC_') &&
typeof process.env[key] === 'undefined'
) {
process.env[key] = combinedEnv[key]
}
}
return combinedEnv
} }
...@@ -266,7 +266,8 @@ export default class HotReloader { ...@@ -266,7 +266,8 @@ export default class HotReloader {
'server', 'server',
this.buildId, this.buildId,
this.previewProps, this.previewProps,
this.config this.config,
[]
) )
let additionalClientEntrypoints: { [file: string]: string } = {} let additionalClientEntrypoints: { [file: string]: string } = {}
......
module.exports = { module.exports = {
// update me
experimental: { experimental: {
async redirects() { async redirects() {
return [ return [
......
...@@ -169,7 +169,28 @@ describe('Env Config', () => { ...@@ -169,7 +169,28 @@ describe('Env Config', () => {
}) })
describe('serverless mode', () => { describe('serverless mode', () => {
let nextConfigContent = ''
const nextConfigPath = join(appDir, 'next.config.js')
const envFiles = [
'.env',
'.env.development',
'.env.development.local',
'.env.local',
'.env.production',
'.env.production.local',
'.env.test',
'.env.test.local',
].map((file) => join(appDir, file))
beforeAll(async () => { beforeAll(async () => {
nextConfigContent = await fs.readFile(nextConfigPath, 'utf8')
await fs.writeFile(
nextConfigPath,
nextConfigContent.replace(
'// update me',
`target: 'experimental-serverless-trace',`
)
)
const { code } = await nextBuild(appDir, [], { const { code } = await nextBuild(appDir, [], {
env: { env: {
PROCESS_ENV_KEY: 'processenvironment', PROCESS_ENV_KEY: 'processenvironment',
...@@ -179,10 +200,22 @@ describe('Env Config', () => { ...@@ -179,10 +200,22 @@ describe('Env Config', () => {
if (code !== 0) throw new Error(`Build failed with exit code ${code}`) if (code !== 0) throw new Error(`Build failed with exit code ${code}`)
appPort = await findPort() appPort = await findPort()
// rename the files so they aren't loaded by `next start`
// to test that they were bundled into the serverless files
for (const file of envFiles) {
await fs.rename(file, `${file}.bak`)
}
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
afterAll(() => killApp(app)) afterAll(async () => {
for (const file of envFiles) {
await fs.rename(`${file}.bak`, file)
}
await fs.writeFile(nextConfigPath, nextConfigContent)
await killApp(app)
})
runTests('serverless') runTests('serverless')
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment